![](/img/trans.png)
[英]Cannot set headers after they are sent to the client with mongoose and node.js
[英]Mongoose Cannot set headers after they are sent to the client
我有這個 Mongoose/Express 代碼,可讓您更新登錄用戶的文檔。 我收到一個錯誤:node:events:368 throw er; // 未處理的“錯誤”事件 ^
錯誤 [ERR_HTTP_HEADERS_SENT]:在將標頭發送到客戶端后無法設置標頭
這是我的代碼。
router.post("/update/:id", checkAuth, (req, res) => {
// check if the snippet was created by the user who is logged in and update the snippet with the new data from the request body
Snippet.findOne({
_id: req.params.id,
userId: req.userData.userId,
})
.then((snippet) => {
if (!snippet) {
return res.status(400).json({
message: "You don't have a snippet with this ID",
});
}
if (req.body.title) {
console.log("if statement");
Snippet.findOne(
{
title: req.body.title,
userId: req.userData.userId,
},
(titleCheckErr, titleCheckSnippet) => {
if (titleCheckErr) {
return res.status(500).json({
error: titleCheckErr,
});
}
if (titleCheckSnippet) {
return res.status(400).json({
message:
"You already have a snippet with that title",
});
}
}
);
snippet.title = req.body.title;
}
snippet.description = req.body.description;
snippet.code = req.body.code;
snippet.language = req.body.language;
// save the snippet
snippet.save((saveSnippetErr, saveSnippet) => {
if (saveSnippetErr) {
return res.status(500).json({
error: saveSnippetErr,
});
}
return res.status(201).json({
message: "Snippet updated",
snippet: saveSnippet,
});
});
})
.catch((err) => {
return res.status(500).json({
error: err,
});
});
});
我想到了。 我把它弄得太復雜了。 我只是將它從使用 mongoose 更改為檢查標題是否存在,並使其成為一個簡單的 if 語句,如果沒有請求正文標題,則從 db 中保持標題相同。 這是代碼。
router.post("/update/:id", checkAuth, (req, res) => {
// check if snippet was created by the user who is logged in, and update the snippet with new data from the request body
Snippet.findOne(
{ _id: req.params.id, userId: req.userData.userId },
(err, snippet) => {
if (err) {
return res.status(500).json({
error: err,
});
}
if (!snippet) {
return res.status(400).json({
message: "Snippet not found",
});
}
if (req.body.title) {
snippet.title = req.body.title;
} else {
snippet.title = snippet.title;
}
snippet.description = req.body.description;
snippet.code = req.body.code;
snippet.language = req.body.language;
// save the snippet
snippet.save((saveErr, saveSnippet) => {
if (saveErr) {
return res.status(500).json({
error: saveErr,
});
}
console.log("updated");
return res.status(201).json({
message: "Snippet updated",
snippet: saveSnippet,
});
});
}
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.