UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

时间:2019-05-11 06:08:14

标签: node.js express

enter image description here当我尝试在同一帖子中发送和接收数据时,出现此错误。我无法解决问题。

但是并不是代码根本不起作用,数据的显示还是很完美的。只是我在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"}));
    })
});

1 个答案:

答案 0 :(得分:2)

您不应多次发送回复,请参见以下内容:

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