简体   繁体   中英

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

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

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

You're calling multiple redirect s, 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");
  }
});

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