Express正在重新发送成功和错误-ERR_HTTP_HEADERS_SENT

时间:2019-08-30 06:22:56

标签: node.js express

我对[ERR_HTTP_HEADERS_SENT]: : Cannot set headers after they are sent to the client有一个奇怪的问题。它位于try/catch中,但是在res.send({message: 'Company set up'})之后还是以某种方式发送了res.send({error}),这是不应该发生的。

我也尝试过return res.send({message: 'Company set up'}),但仍然有相同的错误。除了该错误,我还得到:

(node:19234) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

我发现当await knex()通话被注释掉时没有问题。

try {
      if (req.files) { //multer
        let data = req.body
        const locations = JSON.parse(data.locations)

        const parsedLocations = locations.map((obj, index) => {
          (...)
        })

        await asyncForEach(parsedLocations, async (element, index) => {
          const country = await knex('countries').first().where({ country: element.country })
        })

        console.log('company set up')
        res.send({ message: 'Company set up' })
      }
    } catch (error) {
      console.log('error')
      console.log(error)
      res.send({ error})
    }

这里是asyncForEach函数供参考:

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

来自Node.js的错误日志:

[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/Users/xx/Developer/microservice/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/Users/xx/Developer/microservice/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/xx/Developer/microservice/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/Users/xx/Developer/microservice/node_modules/express/lib/response.js:158:21)
    at router.post (/Users/xx/Developer/microservice/routes/admin.js:714:11)
(node:19337) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)

2 个答案:

答案 0 :(得分:0)

此错误是由于尝试发送多个响应所致。

您可以在返回响应之前检查响应是否已经发送。 喜欢:

if (res.headerSent) {
res.send({ data/ error})

如果已经发送,则不会再发送。

您的代码未捕获该错误。

答案 1 :(得分:0)

return res.status(405).send('User already exist');