Cannot Get/ when express app is deployed on heroku

Viewed 375

my dir structure

/src
   --/public
   --/server.ts
--package.json
--package-lock.json

above is my director structure

app.use(express.static(__dirname + "/public/"));
// app.use(express.static("/public/"));


const path = require("path");


app.get("/", (req, res, next) => {
    // res.sendFile(path.join(__dirname, + "public", 'index.html'));
    res.sendFile(__dirname , "index.html");

    //res.send('Testing one two');
});

const port = process.env.PORT || '5005';
app.listen(port, () => console.log("Server running on port 5005"));

when I run the above code, it works well on my local machine but won't work when it is deployed to Heroku, I tried just passing a string like this and it worked, but when I want to render a static file like the HTML file it wont work on heroku, any help? i think the problem is my directory structure

app.get("/", (req, res, next) => {
      
        res.send('Testing one two');
    });
2 Answers

If I recall correctly, express.static middleware is separate from res.sendFile. In other words, even if you set express.static to public, it will not do anything to res.sendFile, as it takes the first parameter as a path.

In my humble opinion, it would be better if you were to use an absolute path, like the following snippet below.

const path = require('path');

/** Code here... **/

app.get("/", (req, res, next) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

Explanations:

  • path.join is an utility to join path segments into one path. It is cross-platform compatible.
  • __dirname will get the current directory that the script is running from.

Further reading: Express methods.

You just need to give the address of the index.html file in the path for the code mentioned below and paste this code at the end of the inside of the express file and everything will work perfectly fine and you are good to go.

 app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname, './public/index.html'));
      });
Related