Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading