Home > Back-end >  Post request triggering all if else statement and redirecting them
Post request triggering all if else statement and redirecting them

Time:03-08

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

CodePudding user response:

What you are doing wrong is having a loop that sends responses. It is a bad idea. What you wanna achieve could be done in a cleaner way, like so :

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;
  if(data.some(d=>d.fname === n1 && d.pass === n2)){
   return res.redirect("/home");
  }
  res.redirect("/");
 
});

app.get("/home",(req,res)=>{
  res.render("home",{name:nameStore});

Explanation about some method from MDN:

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

More details of what you are doing wrong:

A router handler function should only return one response per request. In your case, if for example the user is not in the data array, you would end up with data.length number of res.redirect("/"); per request.

  • Related