I am creating a login page as my first express project. when I am sending a post request with if/else statement, redirecting them based on input , it is executing all the if else statement and triggering message that header cant set after they are sent to client. After checking other answers, I found that it is running all if else request. So I removed the else statement. It worked fine, but I need a both if/else in order to direct user to pages if their credentials are incorrect. Kindly help on what can I do to remove this error.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended: false}))
var data=[{fname:"john",pass:"dawd123"},{fname:"red",pass:"qwerty"}];
var nameStore="";
app.get("/",function(req,res){
res.render("login");
});
app.post("/",(req,res)=>{
n1 = req.body.uname;
n2 = req.body.password;
for(let i=0;i<data.length;i++){
if(data[i].fname===n1 && data[i].pass===n2){
nameStore = data[i].fname;
res.redirect("/home");
}
else{
res.redirect("/");
}
}
});
app.get("/home",(req,res)=>{
res.render("home",{name:nameStore});
});