Hiero Hiero - 3 months ago 20
Node.js Question

Error: Can't set headers after they are sent. - NodeJS and Express

I have a NodeJS Rest API where I have a user collection, besides that I do user SMS verification.

This is the controller for the POST

/:id/verification


exports.verification = (req, res) => {

const id = req.params.id

return User.find(id)
.then( user => {

if (user.code !== req.body.code) {

res.json({ message: 'Incorrect code' })

res.sendStatus(500)

return

}

user.isVerified = true

user.save( error => {

if (error) {

res.json({ message: 'Failed to update user' })

res.sendStatus(500)

return

}

res.json({ user })

res.sendStatus(200)

} )

} )
.catch( error => {

res.json({ error })

} )

}


But the thing is that when I post to
/:id/verification
I get this error


Error: Can't set headers after they are sent. - NodeJS and Express


On this line:

res.json({ user })
res.sendStatus(200)


But I dont understand why, I dont send any response before this.

Can someone explain me what Im doing wrong?

Answer

you are using both res.json() and res.sendStatus() both together, both of them send response back, That is why it is showing error that Can't set headers after they are sent.

you should use only one of them.

If you want to send status along with the JSON response, you can try this:

res.status(500).json({ message: 'Incorrect code' });

Also, status of 200 is default when using res.send, res.json, etc. So you dont need to send status 200 with res.json()