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
CodePudding user response:
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");
});
CodePudding user response:
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");
}
});