【问题标题】:Error: Can't set headers after they are sent. - NodeJS and Express错误:发送后无法设置标头。 - NodeJS 和 Express
【发布时间】:2016-09-01 21:52:57
【问题描述】:

我有一个 NodeJS Rest API,其中有一个用户集合,此外我还进行用户 SMS 验证。

这是 POST /:id/verification 的控制器

exports.verification = (req, res) => {

  const id = req.params.id

  return User.find(id)
    .then( user => {

      if (user.code !== req.body.code) {

        res.json({ message: 'Incorrect code' })

        res.sendStatus(500)

        return

      }

      user.isVerified = true

      user.save( error => {

        if (error) {

          res.json({ message: 'Failed to update user' })

          res.sendStatus(500)

          return

        }

        res.json({ user })

        res.sendStatus(200)

      } )

    } )
    .catch( error => {

      res.json({ error })

    } )

}

但问题是,当我发布到 /:id/verification 时,我收到了这个错误

错误:发送后无法设置标头。 - NodeJS 和 Express

在这一行:

res.json({ user })
res.sendStatus(200)

但我不明白为什么,在此之前我没有发送任何回复。

谁能解释我做错了什么?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    您同时使用res.json()res.sendStatus(),它们都将response 发回,这就是为什么Can't set headers after they are sent 显示错误。

    你应该只使用其中一个。

    如果您想将状态与 JSON 响应一起发送,您可以试试这个:

    res.status(500).json({ message: 'Incorrect code' });
    

    另外,200 的状态在使用res.sendres.json 等时是default。所以你不需要用status 200 发送status 200res.json()

    【讨论】:

    • 感谢您的回答拉维!
    【解决方案2】:

    res.json() 将对象发送给客户端,然后您尝试使用状态代码设置标头。因此,它显示错误消息。使用以下代码设置状态并同时发送内容。

    res.status(500).json({ error: 'message' } /* json object*/);
    

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 1970-01-01
      • 2017-12-22
      • 2018-09-02
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2019-03-02
      相关资源
      最近更新 更多