1

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Shivam kaushal
  • 173
  • 1
  • 9
  • Your code is calling `res.redirect` multiple times, you for loop alone does it once for every non-match –  Sep 03 '22 at 12:42
  • 1
    Replace `res.redirect` with `return res.redirect`, or more than one redirection may occur, leading to the observed error. – Heiko Theißen Sep 03 '22 at 12:42
  • 2
    Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – ht006 Sep 03 '22 at 13:01

2 Answers2

1

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");
});
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
1

You're calling multiple redirects, one in each iteration of the loop, which causes the error. However, you don't need the loop at all - you can examine public[username] directly (logging removed for brevity's sake):

routes.post("/check", (req, res) => {
  username = req.body.username;
  password = req.body.password;
  if (public[username] === password) {
    console.log("Authenticated success");
    res.redirect("/public");
  } else {
    res.redirect("/404");
  }
});
Mureinik
  • 297,002
  • 52
  • 306
  • 350