Error: Cannot set headers after they are sent to the client (with next)

Error: Cannot set headers after they are sent to the client (with next)

我正在尝试进行一些数据库查询并检查一些数据。如果某些条件不匹配,它应该创建一个错误并使用 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]:发送给客户端后无法设置headers

return returns 仅来自当前回调函数,它不会以任何方式停止承诺链。您正在寻找

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'});
    }
});