Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client error occured while using redirect in nodejs

Issue

I am making a project where I am facing this error. What I wanted to do is that according to the condition it should redirect the server to the particular routes but getting this error.

routes.post("/check", (req, res) => {
  console.log("/check");
  //   console.log(req.body);
  username = req.body.username;
  password = req.body.password;
  console.log("Step 1");
  console.log("Username:", username, "\n", "Password", password);
  console.log(public);
  for (let i in public) {
    if (username === i && password === public[i]) {
      console.log("Authenticated success");
      res.redirect("/public");
    } else {
      res.redirect("/404");
    }
  }
  res.redirect("/public");
});

Output is

/check
Step 1
Username: shivam2 
 Password 4321
{ shivam2: '4321', arjun2: 'dcba' }
Authenticated success
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Solution

You should return in case of successful authentication:

routes.post("/check", (req, res) => {
  console.log("/check");
  //   console.log(req.body);
  username = req.body.username;
  password = req.body.password;
  console.log("Step 1");
  console.log("Username:", username, "\n", "Password", password);
  console.log(public);
  for (let i in public) {
    if (username === i && password === public[i]) {
      console.log("Authenticated success");
      return res.redirect("/public");
    } 
  }
  res.redirect("/404");
});

Answered By – lpizzinidev

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