Stichiboi
Stichiboi

Reputation: 119

res.sendFile() Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

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

Upvotes: 5

Views: 1370

Answers (1)

boolfalse
boolfalse

Reputation: 2131

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:

Upvotes: 3

Related Questions