node.js - UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
问题描述
当我尝试在同一个帖子中发送和接收数据时,我会收到此错误。我无法找出问题所在。
但这并不是代码根本不起作用,数据显示得非常好。只是我在 bash 控制台中遇到了这个错误。
router.post('/add',(req, res) => {
const newAMCReg = new AMCReg({
amcrefno: req.body.amcrefno,
amcregdate: req.body.amcregdate,
customer: req.body.customerid,
customertype: req.body.customertypeid,
department: req.body.customersubdepartmentid,
serviceprovider: req.body.serviceproviderid,
amcstartdate: req.body.amcstartdate,
amcexpiredate: req.body.amcexpiredate,
remarks: req.body.remarks
});
newAMCReg.save()
.then((amcid) => {
AMCReg.findOne({amcrefno: req.body.amcrefno})
.then(amc => res.json(amc))
.then(amc => {
res.status(200).json({ msg: "AMC Registration Updated Successfully" });
})
.catch(err => res.status(500).json({msg: "Internal Server Error"}));
})
});
解决方案
您不应多次发送回复,请参见下文:
router.post('/add', (req, res) => {
const newAMCReg = new AMCReg({
amcrefno: req.body.amcrefno,
amcregdate: req.body.amcregdate,
customer: req.body.customerid,
customertype: req.body.customertypeid,
department: req.body.customersubdepartmentid,
serviceprovider: req.body.serviceproviderid,
amcstartdate: req.body.amcstartdate,
amcexpiredate: req.body.amcexpiredate,
remarks: req.body.remarks
});
newAMCReg.save()
.then((amcid) => {
AMCReg.findOne({
amcrefno: req.body.amcrefno
})
.then(amc => {
res.status(200).json({
msg: "AMC Registration Updated Successfully",
data: amc
});
})
.catch(err => res.status(500).json({
msg: "Internal Server Error"
}));
})
});
推荐阅读
- microsoft-graph-api - 无法在启动配置服务.Net 5.0 中添加 AddMicrosoftGraph
- pine-script - 如何在 pinescript 中访问(私有)自定义指标的值?
- javascript - Material-UI TreeView TreeItems 背景
- swift - 在 Swift 中通过正则表达式替换大量字符串的更快方法
- c++ - 初始化数组对 C++ 性能有显着影响吗?
- java - 如何在代码覆盖中包含 Catch 块:JaCoCo 和 Junit
- android - 将手机更新到 Android 11 后无法保存 pdf 文件
- flutter - 依赖冲突
- angular - 错误处理程序被调用两次 angular http_interceptor
- python - 如何在 python 中生成三个随机数作为满足向量大小的向量分量