Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Post request triggering all if else statement and redirecting them

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});
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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 this:

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda