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

标签 node.js promise sequelize.js 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]:发送到客户端后无法设置 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/

相关文章:

javascript - then/promises 不能在 for 循环后使用变量

node.js - 如何返回刚刚创建的行及其与 sequelize 的关联

node.js - 多次测试运行后的 Sequelizejs/未知关系 "xxx"

javascript - 部署到Heroku node-gyp无法安装base64@2.1.0,node-gyp重建失败

javascript - Pageres (phantomjs) 不返回 promise

javascript - ES6 类静态方法 vs 函数

javascript - 为什么 deferred.when() 在完成回调中返回 promise ?

javascript - 在 NodeJs 中使用 tedius 和 sequelize 的 SQL Server 连接

javascript - 如何在没有 NPM 的 "require"的情况下使用 React ?

javascript - 'react-scripts' 未被识别为内部或外部命令