![](/img/trans.png)
[英]Getting Can't set headers after they are sent after res.send() in express js
[英]Express return res.send get Error: Can't set headers after they are sent
我搜索這個錯誤是由res.send
引起的兩次。 解決方案應該使用return res.send
。
但它對我不起作用。
這是我的代碼:
function editFoo(req, res) {
ErrorResponse.checkError422(req, res)
console.log("shouldn't print")
Foo.findAndUpdate({_id:req.params.activityId}, {$set:{title:req.body.title}}, {new: true}, function(err, activity) {
return res.send({code: 0, newTitle: activity.title, message: "Edit successfully"})
})
}
ErrorResponse.js
function checkError422(req, res) {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).send({error: "xxx"})
}
}
module.exports = { checkError422 }
然后我得到了錯誤:
Error: Can't set headers after they are sent.
並且shouldn't print
。
但如果我直接用檢查錯誤代碼替換了ErrorResponse.checkError422(req, res)
,
function editFoo(req, res) {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).send({error: "xxx"})
}
console.log("shouldn't print")
Foo.findAndUpdate({_id:req.params.activityId}, {$set:{title:req.body.title}}, {new: true}, function(err, activity) {
return res.send({code: 0, newTitle: activity.title, message: "Edit successfully"})
})
}
運作良好,不打印“ shouldn't print
”
不知道這里有什么問題。 我想使用checkError422
函數來替換許多檢查。 我認為return res.status(422).send({error: "xxx"})
應退出此editFoo
。
為什么? 謝謝您的幫助。
我在你的代碼中看到checkError422
可以res
仍然發送一個答案...所以你必須做反...
// checkError422
if (!errors.isEmpty()) {
return res.status(422).send({error: "xxx"})
}
所以:
function editFoo(req, res) {
const errors = validationResult(req)
if (errors.isEmpty()) {
console.log("shouldn't print")
Foo.findAndUpdate({_id:req.params.activityId}, {$set:{title:req.body.title}}, {new: true}, function(err, activity) {
return res.send({code: 0, newTitle: activity.title, message: "Edit successfully"})
})
}
}
更新
你的代碼是redondant,所以你只需要做:
function checkError422(req, res) {
return validationResult(req)
}
module.exports = { checkError422 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.