I'm using express to build a simple server. Everything works, but I'm getting this annoying error in the console every time I try to hard-refresh (cntr + R) my page.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Here is the code:
app.get('/index', (req, res) => {
const filePath = path.join(__dirname, 'public', 'index.html');
console.log(res.headersSent);
res.sendFile(filePath);
});
The console.log(res.headersSent) is there to check that indeed, the headers are NOT set (it logs false every time).
I tried sending a simple JSON instead of a file, and no error occurs:
app.get('/index', (req, res) => {
const filePath = path.join(__dirname, 'public', 'index.html');
console.log(res.headersSent);
res.json({status: 'All good'});
});
The error occurs only when I'm using res.sendFile(). The index.html will request an index.js file once it loads. Maybe that's the issue? But isn't it a different request?
Thank you!
EDIT I've tried checking for errors in the callback function of sendFile(). It's undefined, even though the console keeps spitting out the "Cannot set headers" error