gpt4 book ai didi

node.js - 错误 : Cannot set headers after they are sent to the client (with next)

转载 作者:行者123 更新时间:2023-12-03 22:27:02 28 4
gpt4 key购买 nike

我正在尝试进行一些数据库查询并检查一些数据。如果某些条件不匹配,它应该创建一个错误并使用 next(err) 转发。

问题是,它向我发送错误作为响应,但它试图继续。所以我的 node.js 应用程序出现错误。

Purchase.findAndCount({where: {fk_product: productId, fk_buyer: req.decoded.id}}).then((numPurchases) => {
// product purchased?
if (numPurchases.count < 1) {
const errNotBought = new Error("you did not buy this product");
errNotBought.status = 403;
return next(errNotBought); // <--- it should break up here
}
}).then(() => {
res.send({status: true, data: 'product'}) // <-- stacktrace point this line
})

错误是:未处理的拒绝错误[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 header

最佳答案

return 仅从当前回调函数返回,它不会以任何方式停止 promise 链。你正在寻找

Purchase.findAndCount({where: {fk_product: productId, fk_buyer: req.decoded.id}}).then(numPurchases => {
// product purchased?
if (numPurchases.count < 1) {
const errNotBought = new Error("you did not buy this product");
errNotBought.status = 403;
next(errNotBought); // <--- it should break up here
} else {
res.send({status: true, data: 'product'});
}
});

关于node.js - 错误 : Cannot set headers after they are sent to the client (with next),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54387779/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com