我不知道为什么这个错误不断出现。我在互联网上搜索了所有可能的解决方案,但仍然没有找到。这是我用于 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/