我有一个 NodeJS Rest API,其中有一个用户集合,此外我还进行用户短信验证。
这是 POST /:id/verification
的 Controller
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 })
} )
}
但问题是,当我发布到 /:id/verification
时,我收到此错误
Error: Can't set headers after they are sent. - NodeJS and Express
在这一行:
res.json({ user })
res.sendStatus(200)
但我不明白为什么,在此之前我没有发送任何回复。
有人可以解释一下我做错了什么吗?
最佳答案
您同时使用了res.json()
和res.sendStatus()
,它们都发送响应
,这就是为什么它显示错误发送后无法设置 header
。
您应该只使用其中之一。
如果您想将状态与 JSON 响应一起发送,您可以尝试以下操作:
res.status(500).json({ message: 'Incorrect code' });
此外,当使用 res.send
、res.json
等时,200
的状态是default
。因此,您不需要使用 res.json()
发送 status 200
关于node.js - 错误 : Can't set headers after they are sent. - NodeJS 和 Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273196/