Home > Software engineering >  Nodejs res.status().send() returns "Cannot set headers after they are sent to the client"
Nodejs res.status().send() returns "Cannot set headers after they are sent to the client"

Time:03-13

I have a nodejs react app where I fetch some data to the server:


await fetch(`${process.env.NEXT_PUBLIC_DR_HOST}/validate`, {
    method: 'POST',
    body: valBody,
    headers: { 'Content-Type': 'application/json' }
})

After that, the data will be validated to see if there are any errors within its content. If everything is fine, a 200 status code is returned (manually or by default) back as response, and then something else should happen:

.then(res =>
{
     console.log(res)
     if (res.status === 200)
     {
    //do stuff

If there is an error, a 400 code will be sent

 if (error)
    {
        const msg = error.details.map(e => e.message).join(',') //
        res.status(400).send("Invalid Data")
        throw new ServerError("Invalid Data", 400)
    }

Sending only res.status(400) without .send will only return a 200 res. Everything works fine but an error is thrown: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. This happens only because I send a message after the status code res.status(400).send("Invalid Data"), but as I said, returning only a status code res.status(400) will not affect the response status leaving it to 200. What should I do?

CodePudding user response:

It's also possible that

throw new ServerError("Invalid Data", 400)

is causing the problem. A synchronous exception in a request handler will be caught by express and it will attempt to send an error response, but you've already done

res.status(400).send(...)

So, remove either the throw new ServerError("Invalid Data", 400) or the res.status(400).send("Invalid Data"). Don't have both. That's a guess, we need to see the WHOLE request handler to know for sure what to suggest. And, depending upon how the code is structured, you may also need a return to keep any other code paths from executing.

  • Related