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.