0

I have simple server.js file as follows:

const express = require('express');
const app = express();

app.set('port', (process.env.PORT || 3031));

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('build'));
  app.get('*', (req, res) => {
    res.sendFile('build/index.html');
  })
}

app.listen(app.get('port'), (error) => {
  if (error) return console.error(error.message);
  console.log(`Server started at: http://localhost:${app.get('port')}/`);
})

I expect it to re-route all paths to index.html in production and start a server. At the moment routing bit seems to not work, as I am getting following error:

Server started at: http://localhost:3031/ TypeError: path must be absolute or specify root to res.sendFile

Ilja
  • 44,142
  • 92
  • 275
  • 498

2 Answers2

0

Try adding the root directory to the path

res.sendFile(__dirname + '/build/index.html');
Mattliff
  • 61
  • 5
0

res.sendFile requires an absolute path, just as the error says.

Try using the __dirname global:

res.sendFile(__dirname + 'build/index.html');

Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45