[英]Node JS throwing cannot set headers after they are sent to the client, after using mongoose.removeOne
I have a method that deletes products and before it does it check if the user who is trying to delete the product is the user who created it.我有一种删除产品的方法,在它执行之前检查尝试删除产品的用户是否是创建它的用户。 When i execute it with Insomnia it successfully removes the product but i get an error on the console saying cannot set headers after they are sent to the client.
当我使用 Insomnia 执行它时,它成功删除了产品,但我在控制台上收到错误消息,提示无法在将标头发送到客户端后设置标头。
My method:我的方法:
exports.deleteProduct = (req, res) => {
const id = req.params.productId;
Product.deleteOne({ _id: id, userId: req.user._id }, () => {
return res.status(401).json("Not authorized");
})
.then(() => {
return res.status(200).json("Product deleted");
})
.catch((err) => {
return res.status(500).json({
error: err,
});
});
};
I'm pretty sure this is happening because I'm chaining a.then() and.catch() after executing it.我很确定这正在发生,因为我在执行它之后链接了 a.then() 和 .catch() 。
I tried to do this but it didn't work because the err parameter that I'm sending to the callback function is null.:我尝试这样做,但没有成功,因为我发送给回调 function 的 err 参数是 null。:
exports.deleteProduct = (req, res) => {
const id = req.params.productId;
Product.deleteOne({ _id: id, userId: req.user._id }, (err) => {
if (err) {
return res.status(401).json("Not authorized");
}
return res.status(200).json("Product deleted");
});
};
When i tried this second approach I always got the 200 status, meanwhile the product didn't delete.当我尝试第二种方法时,我总是得到 200 状态,同时产品没有删除。
Any idea how to deal with this?知道如何处理这个问题吗?
You can try something like this:你可以尝试这样的事情:
Product.deleteOne({ _id: id, userId: req.user._id }, (err, result) => {
if(err) {
return "something"
}
return "something else"
});
or: in async / await way或:以异步/等待方式
try {
await Product.deleteOne({ _id: id, userId: req.user._id });
} catch (err) {
// handle error here
}
By the way, why you are passing userId
at the deleteOne
method?顺便说一句,为什么你在
deleteOne
方法中传递userId
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.