node.js - 未处理的 promise 拒绝 : Cannot set headers after they are sent to the client

标签 node.js angular api express header

我不知道为什么这个错误不断出现。我在互联网上搜索了所有可能的解决方案,但仍然没有找到。这是我用于 API 调用的 Node 函数。

exports.GetEmployeeConfirmationList = function (req, res) {
    var request = dbConn.request();
    request.execute(storedProcedures.GetEmployeeConfirmationList).then(function (response) {
        res.status(200).send({
            success: true,
            data: response.recordset
        });
    }).catch(function (err) {
        res.status(200).send({
            success: false,
            message: err.message
        });
    });
};

如何克服这个问题? 提前致谢。

最佳答案

修改您的代码以使用箭头函数,因为 res 对象正在失去其作用域。 当调用 GetEmployeeConfirmationList 回调时,它不知道 res 对象,因此它是 undefined。因此,在执行 res.status 时,它抛出异常并进入 catch block ,在那里它再次执行 res.status 并再次中断并导致未处理的 promise 拒绝。 您可以捕获 err 对象并在 finally block 中将其log 以检查它是否正在发生。

exports.GetEmployeeConfirmationList = function (req, res) {
    var request = dbConn.request();
    request.execute(storedProcedures.GetEmployeeConfirmationList).then((response) => {
        res.status(200).send({
            success: true,
            data: response.recordset
        });
    }).catch((err) => {
        res.status(200).send({
            success: false,
            message: err.message
        });
    });
};

关于node.js - 未处理的 promise 拒绝 : Cannot set headers after they are sent to the client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50577693/

相关文章:

node.js - 在 bluebird/bookshelf.js 中,tap 函数是做什么的

javascript - Node 调度仅运行一次

node.js - 使用多个命令将命令行参数传递给 npm 'pre' 脚本和脚本

Angular 2 的双向绑定(bind)不适用于 Electron 应用程序的初始加载

用于在联系人在线时收到通知的 Android Whatsapp API

node.js - 如何通过nodejs使用Apache Ignite空间功能?

Angular2 - 如何链接异步 http 请求并在失败时停止

angular - 在 Angular 2/Typescript 中用括号显示负货币

jquery - 使用 Instagram API 获取一组随机照片

javascript - 数据绑定(bind)剑道 ui 网格与外部 API