【问题标题】:Cannot set headers after they are sent to the client, NodeJs Error将标头发送到客户端后无法设置标头,NodeJs 错误
【发布时间】:2019-11-06 06:38:36
【问题描述】:

我收到一个名为“错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头”的错误。这是我的代码

router.post('/patent', upload.array('patentFiles', 2), (req, res) => {
  var id = req.body.id
  var patentFile = req.files
  res.send(patentFile)

  Patent.findOne({ id: id }, (err, doc) => {
    if (doc) {
      res.status(404).send('Already Exists!')
    } else {
      var insertPatentRecord = new Patent({
        id: id
      })
      insertPatentRecord.save((err, doc) => {
        if (err) {
          res.send(err)
        } else {
          res.send({
            msg: 'Saved',
            doc: doc
          })
        }
      })
    }
  })
})

非常感谢

【问题讨论】:

  • 您有res.send(patentFile),然后在find 查询结果之后再次出现。一旦响应已经发送,你就不能这样做了。
  • 你为什么要把patentFile发回给客户?

标签: node.js


【解决方案1】:

一旦您将响应发送回客户端,对响应方法的任何进一步调用都将导致“无法在将标头发送到客户端后设置标头”错误。为避免这种情况,请在响应调用之前放置 return。像这样:

return res.send(patentFile)

但是查看响应的位置并看到您也在对专利集合进行查询之后,您可能想要更改res.send(patentFile) 的位置。

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 2021-10-24
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    相关资源
    最近更新 更多