[英]UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clien
I get error: "UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client", guessing that the problem is with promises, but I don't understand how to fix it.我收到错误:“UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client”,猜测问题出在 Promise 上,但我不明白如何解决。
How do I fix my code to avoid this error, but keep the logic and work with the database?如何修复我的代码以避免此错误,但保留逻辑并使用数据库?
router.post("/addNote", (req, res) => {
let currentTime = new Date();
currentTime.setUTCHours(currentTime.getUTCHours() + 3);
const post = new PostModel({
title: req.body.inputHeader,
text: req.body.inputText,
author: req.body.author,
createdAt: currentTime
});
post.save().then(() => {
res.json({status: "saved"});
})});
router.get("/getNotes", (req, res) => {
PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
if (err)
res.json(err);
res.json(notes);
});
});
router.delete("/deleteNote/:id", (req, res) => {
PostModel.deleteOne(
{
_id: req.params.id
}
).then((notes) => {
if (notes)
res.json({status: "deleted"});
res.json({status: "error while deleting"});
});
});
router.put("/updateNote/:id", (req, res) => {
PostModel.findByIdAndUpdate(
req.params.id,
{
$set: req.body
},
err => {
if (err)
res.send(err);
res.send({status: "updated"})
}
).then((notes) => {
if (notes)
res.json({status: "update"});
res.json({status: "error while updating"});
});
});
router.get("/getNote", (req, res) => {
PostModel.findOne({ _id: req.params.id}).then(post => {
if (!post){
res.send({error: "not found"});
} else {
res.json(post)
}
});
});
router.post("/authorize", (req, res) => {
// bcrypt.hash ("", saltRounds, (err, hash) => {
// console.log(hash);
// });
let resultAuthorization = false;
if (req.body.login === authorization.login) {
resultAuthorization = bcrypt.compareSync(req.body.password, authorization.password);
}
if (resultAuthorization)
res.json({statusAuthorization: "correct"});
res.json({statusAuthorization: "incorrect"});
});
module.exports = router;
The problem is that you are calling res.json
several times in one handler.问题是您在一个处理程序中多次调用
res.json
。 When calling it a second time a response has already been sent so you can not send another response.当第二次调用它时,已经发送了响应,因此您无法发送另一个响应。
As tkausl already pointed out you are missing else
s so that res.json
is being called once.正如 tkausl 已经指出的那样,您缺少
else
,因此res.json
被调用一次。
You need to change your handlers similar to the /getNote
handler.您需要更改类似于
/getNote
处理程序的处理程序。
The handler for the endpoint deleteNode/:id
for example has to be changed to this:例如,端点
deleteNode/:id
的处理程序必须更改为:
router.delete("/deleteNote/:id", (req, res) => {
PostModel.deleteOne(
{
_id: req.params.id
}
).then((notes) => {
if (notes)
res.json({status: "deleted"});
else
res.json({status: "error while deleting"});
});
});
This else
also needs to be added in /getNotes
and /authorize
.这个
else
也需要添加到/getNotes
和/authorize
中。
The reason is you're trying to send a response more than once.原因是您尝试多次发送响应。 Once the response is returned, if the program sends a response again, this error occurs.
一旦返回响应,如果程序再次发送响应,就会出现这个错误。 The reason for the problem is that you do not return the current function after the if condition.
出现问题的原因是您在 if 条件之后没有返回当前的 function。 Let me explain with some codes
让我用一些代码来解释
router.get("/getNotes", (req, res) => {
PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
if (err) {
res.json(err);
console.log('We encountered an error and sent the error as a response. But our function still continue...');
}
res.json(notes);
console.log('We tried to sent successfull response but function still continue');
});
});
So after the response, you should end the function or make sure that you do not call any other response function in the ongoing code stream/flow.因此,在响应之后,您应该结束 function 或确保在正在进行的代码流/流中不调用任何其他响应 function。 Lets fix your code.
让我们修复您的代码。
router.get("/getNotes", (req, res) => {
PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
if (err) {
return res.json(err);
// It is not will be continued because the function returned with response.
}
return res.json(notes);
console.log('No console output')// It is will not be called because function returned.
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.