-2

A full overview and answer can be find in the first answer: Error: Can't set headers after they are sent to the client

I am using:

  • Express
  • mongoose (for MongoDB)

In registering new users, I wanted to check if the user's email or name already exist (cause they have to be unique).

I had this piece of code:

    try {
  let user = await User.findOne({ email })

  if (user) {
    res
      .status(400)
      .json({ status: 'error', body: [{ msg: 'email already exist' }] })
  }

  user = await User.findOne({ name })

  if (user) {
    res
      .status(400)
      .json({ status: 'error', body: [{ msg: 'name already exist' }] })
  }

// ... some more code

} catch(err) {

//... code

}

I was keep getting: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. Terminal doesn't show the exact place the error is created.

  • 2
    You should `return res...`, otherwise the method continues even if you've already tried to respond. – jonrsharpe Dec 30 '20 at 14:27
  • Thanks for the super quick response! I was posting this to write the solution myself (realize that after wasting some time...) to help others. Thanks anyway! – David L. Rajcher Dec 30 '20 at 14:28

2 Answers2

1

The response were res.status(400).json({ ... }) and not return res.status(400).json({ ... }).

Because of that, the code went on to the second condition and tried again to send a response, BUT express let us know that the response was already sent and it cannot change those resposne anymore...

The solution was quite simple - add return and make sure this code stops before trying to send another response.

1

I had the same problem but with a typo trying to send 2 times the response into my function. It seems its your case too. As mentioned by @David, the return statement makes a go out of the function...

resp.send('OK')
do_stuff
resp.send('OK')
Pipo
  • 4,653
  • 38
  • 47