【问题标题】:Express return res.send get Error: Can't set headers after they are sentExpress return res.send get Error: Can't set headers after they are sent
【发布时间】:2019-05-05 15:39:56
【问题描述】:

我搜索了这个错误是由res.send引起的两次。该解决方案应使用return res.send

但这对我不起作用。

这是我的代码:

function editFoo(req, res) {
  ErrorResponse.checkError422(req, res)
  console.log("shouldn't print")
  Foo.findAndUpdate({_id:req.params.activityId}, {$set:{title:req.body.title}}, {new: true}, function(err, activity) {
        return res.send({code: 0, newTitle: activity.title, message: "Edit successfully"})
    })
}

ErrorResponse.js

function checkError422(req, res) {
  const errors = validationResult(req)

  if (!errors.isEmpty()) {
    return res.status(422).send({error: "xxx"})
  }
}

module.exports = { checkError422 }

然后我得到了错误:

Error: Can't set headers after they are sent.

shouldn't print 打印出来。

但是如果我直接将ErrorResponse.checkError422(req, res)替换为检查错误码,

function editFoo(req, res) {
      const errors = validationResult(req)

      if (!errors.isEmpty()) {
        return res.status(422).send({error: "xxx"})
      }
      console.log("shouldn't print")
      Foo.findAndUpdate({_id:req.params.activityId}, {$set:{title:req.body.title}}, {new: true}, function(err, activity) {
            return res.send({code: 0, newTitle: activity.title, message: "Edit successfully"})
        })
    }

效果很好,不打印“shouldn't print

不知道这里出了什么问题。我想使用checkError422 函数来替换许多检查。我觉得 return res.status(422).send({error: "xxx"}) 应该退出这个editFoo

为什么?感谢您的帮助。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    我看到在你的代码中checkError422 可以res 仍然发送一个答案...所以你必须做相反...

      // checkError422
      if (!errors.isEmpty()) {
        return res.status(422).send({error: "xxx"})
      }
    

    所以:

    function editFoo(req, res) {
          const errors = validationResult(req)
    
          if (errors.isEmpty()) {
               console.log("shouldn't print")
               Foo.findAndUpdate({_id:req.params.activityId}, {$set:{title:req.body.title}}, {new: true}, function(err, activity) {
                    return res.send({code: 0, newTitle: activity.title, message: "Edit successfully"})
               })
          }
        }
    

    更新

    你的代码是多余的,所以你只需要这样做:

    function checkError422(req, res) {
      return validationResult(req)
    }
    
    module.exports = { checkError422 }
    

    【讨论】:

    • 我也想返回错误。不知道为什么checkError422 不使用return res.send... 退出函数?
    猜你喜欢
    • 2014-12-23
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多