4

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

Stichiboi
  • 79
  • 1
  • 5
  • "But isn't it a different request?" Yes, but from what you're saying it sounds the index.js endpoint may result in headers being sent twice. – IAmDranged Apr 27 '21 at 19:59

1 Answers1

2

sendFile is asynchronous function, so you need to send response after the engine reads the file, but json is synchronous instead (that's why it didn't thrown an error for that).

In other words, you need to send the response from the callback, something like this:

app.get('/index', (req, res) => {
    const filePath = path.join(__dirname, 'public/index.html');
    res.sendFile(filePath, function(err) {
        if (err) {
            return res.status(err.status).end();
        } else {
            return res.status(200).end();
        }
    });
});

For more, read read these:

boolfalse
  • 1,892
  • 2
  • 13
  • 14
  • Note the sendFile() function doesn't just read the file - it actually sends a response to the client. You shouldn't try and send another response from the callback. – IAmDranged Apr 27 '21 at 20:03
  • Yep.. also it's good practice to send back the response with "return" – boolfalse Apr 27 '21 at 20:10
  • I've tried using the callback, and now I'm getting the Error twice XD. The weird thing is that the error in the callback function is undefined – Stichiboi Apr 28 '21 at 08:03