[英]NodeJs Middleware does not working properly to avoid duplication of data submission
我編寫了一個中間件,以避免重復提交相同的數據。 似乎可以防止重復,但是它不提交新數據。 我收到錯誤消息“發送后無法設置標題”。 有什么方法可以防止這種情況發生?
中間件
function checkDuplication(req, res, next) {
if (req.isAuthenticated()) { // is user logged in?
User.findById(req.params.id, function(err, foundUser) {
if (err) {
res.redirect('back');
console.log(err);
} else {
for (var index = 0; index < foundUser.friendRequest.length; index++) {
if ((foundUser.friendRequest[index].id.toString()) ===
(req.user._id.toString())) {
console.log("you are already in his friends list ");
break;
} else { //so is there is any way that I can only run this line
//once outside the loop and avoid several response by express
console.log("one friend added");
next();
}
}
res.redirect("back");
}
})
} else {
res.redirect('back');
}
}
//Post route to submit a data
router.post("/people/friendRequest/:id", checkDuplication,
function(req, res) {
User.findById(req.params.id, function(err, user) {
if (err) {
throw err;
} else {
var Request = {
id: req.user._id,
username: req.user.username
}
user.friendRequest.push(Request);
user.save();
res.redirect("back"); //getting error due this line
}
})
res.redirect("back");
})
您可以使用數組函數來檢查是否有任何符合條件的項目:
if (foundUser.friendRequest.some((fr) => fr.id.toString() === req.user._id.toString())) {
console.log("you are already in his friends list ");
res.redirect("back");
} else {
next();
}
這將遍歷數組,直到找到匹配項,此時它將調用`res.redirect(“ back”)。
如果找不到匹配項,它將調用next()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.