Program works but I keep getting "Cannot set headers after they are sent to the client", should I ignore it?

Issue

I don’t know if this is enough code to post, but this is the line that is causing my the error: (The res.redirect) line

app.post("/home/finishform",urlencodedParser, (req,res)=>{

  const score = new Score(req.body)

  score.save()
    .then((result)=>{
      res.redirect("/")
    }).catch((err)=>{
      console.log(err)
    })
  res.redirect("/home/FinishPage/client")// This is causing the error, but it's actually redirecting, so it's working but I keep getting an error. 
})

Solution

You have two calls to redirect, which causes the error. You should probably only redirect if the saving was successful:

app.post("/home/finishform",urlencodedParser, (req,res)=>{

  const score = new Score(req.body)

  score.save()
    .then((result)=>{
      res.redirect("/home/FinishPage/client") // Here!
    }).catch((err)=>{
      console.log(err)
    })
})

Answered By – Mureinik

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published