node.js - 错误 : Can't set headers after they are sent. - NodeJS 和 Express

标签 node.js express mongoose

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

这是 POST /:id/verification 的 Controller

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 时,我收到此错误

Error: Can't set headers after they are sent. - NodeJS and Express

在这一行:

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

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

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

最佳答案

您同时使用了res.json()res.sendStatus(),它们都发送响应,这就是为什么它显示错误发送后无法设置 header

您应该只使用其中之一。

如果您想将状态与 JSON 响应一起发送,您可以尝试以下操作:

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

此外,当使用 res.sendres.json 等时,200 的状态是default。因此,您不需要使用 res.json() 发送 status 200

关于node.js - 错误 : Can't set headers after they are sent. - NodeJS 和 Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273196/

相关文章:

node.js - MongoDb 适合我的应用程序吗?

node.js - Mongoose API 通过 _id 获取数组中的嵌套项

javascript - Sails.js - 如何避免 Sails JS 在数据库表上查找 Id(因为该表没有 id 列)

node.js - 使用 angular2 应用程序发送的 Express.js 接收 POST 数据

javascript - mongodb/mongoose findAndModify setoninsert

javascript - Passport mongoose Object #<Schema> 没有方法 'authenticate' 但我可以看到该方法

node.js - 如何使用 http-proxy 隐藏 Node.js 服务器

node.js - 核心 Node.js 中的express.js "app.use()"相当于什么?

node.js - 使用express和passport未设置cookie

javascript - 在 Mongoose 模式中将一个数组写入另一个数组中