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

后端 未结 2 1400
日久生厌
日久生厌 2021-01-26 03:32

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

相关标签:
2条回答
  • 2021-01-26 03:52

    res.json() send object to the clilent and after that you are trying to set the header with status code. So, it shows the error message. Use following code for set status and sending the content in the same time.

    res.status(500).json({ error: 'message' } /* json object*/);
    
    0 讨论(0)
  • 2021-01-26 04:02

    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()

    0 讨论(0)
提交回复
热议问题