首页 > 解决方案 > 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"}));
    })
});

标签: node.jsexpress

解决方案


您不应多次发送回复,请参见下文:

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


推荐阅读