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

时间:2016-09-01 13:42:48

标签: node.js express mongoose

我有一个NodeJS Rest API,我有一个用户集合,除了我做用户短信验证。

这是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)

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

有人可以解释一下我做错了吗?

2 个答案:

答案 0 :(得分:3)

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

你应该只使用其中一个。

如果您想发送状态以及JSON响应,可以尝试:

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

此外,使用200default等时,res.send的状态为res.json。因此,您无需使用{{1}发送status 200 }

答案 1 :(得分:1)

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

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