有一个要求,只有在找到产品和用户时才能添加评论。所以我编写了代码来实现这个场景。
User.findById(req.params.userId).exec()
.then(response => {
console.log("response", response);
if (response) {
return Product.findById(req.params.productId).exec();
}
else {
return res.status(404).json({
message: 'User not found'
})
}
})
.then(response => {
console.log("response", response);
if (!response) {
return res.status(404).json({
message: 'Product not found'
})
}
const review = new Review({
_id: mongoose.Types.ObjectId(),
rev: req.body.rev,
productId: req.params.productId,
userId: req.params.userId
});
return review.save();
})
.then(response => {
console.log("responseeeeeeee", response);
res.status(201).json({
response
})
})
.catch(error => {
console.log("error", error);
res.status(500).json({
error
})
})
这工作正常,但一旦产品或用户丢失,它就会发出警告:
(node:17276) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (D:\backup-learning\project-shop-always\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (D:\backup-learning\project-shop-always\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (D:\backup-learning\project-shop-always\node_modules\express\lib\response.js:267:15)
at User.findById.exec.then.then.then.catch.error (D:\backup-learning\project-shop-always\api\controllers\review-controller.js:58:29)
at process._tickCallback (internal/process/next_tick.js:68:7)
浮云间
相关分类