错误:发送标头后无法设置. -NodeJS和Express [英] Error: Can't set headers after they are sent. - NodeJS and Express
问题描述
我有一个NodeJS Rest API,其中有一个用户集合,此外我还进行用户SMS验证.
I have a NodeJS Rest API where I have a user collection, besides that I do user SMS verification.
这是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 })
} )
}
但是问题是,当我发布到/:id/verification
时,我会收到此错误
But the thing is that when I post to /:id/verification
I get this error
错误:发送标头后无法设置标头. -NodeJS和Express
Error: Can't set headers after they are sent. - NodeJS and Express
在这一行:
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?
推荐答案
您同时使用了res.json()
和res.sendStatus()
,它们都将response
发送回去,这就是为什么它显示
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.
如果您想随JSON响应一起发送状态,可以尝试以下操作:
If you want to send status along with the JSON response, you can try this:
res.status(500).json({ message: 'Incorrect code' });
此外,在使用res.send
,res.json
等时,200
的状态为default
.因此,您无需将status 200
与res.json()
一起发送
Also, status of 200
is default
when using res.send
, res.json
, etc. So you dont need to send status 200
with res.json()
这篇关于错误:发送标头后无法设置. -NodeJS和Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!