简体   繁体   中英

Express return res.send get Error: Can't set headers after they are sent

I searched this error is caused by res.send twice. The solution should use return res.send .

But It doesn't work for me.

Here is my code:

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 }

Then I got the error:

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

and shouldn't print printed.

But if I replaced ErrorResponse.checkError422(req, res) by the check error code directly,

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"})
        })
    }

works well and not print " shouldn't print "

Not sure what's wrong here. I want to use checkError422 function to replace many checks. I think the return res.status(422).send({error: "xxx"}) should exit this editFoo .

Why? Thanks for the help.

I see that in your code the checkError422 can the res still send an answer... so You have to do the inverse...

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

So :

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"})
           })
      }
    }

Update

your code is redondant, so you just have to do :

function checkError422(req, res) {
  return validationResult(req)
}

module.exports = { checkError422 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM