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

148
Visualizações
res.redirected returning false even when the backend returns a redirect

I'm trying to create a login page which redirects the user back to the home page after successful login using nodejs and fetch. Here is the code of backend.

app.post('/login',(req,res)=>
{
    user.findOne(req.body,(err,info)=>{
        if(err)
        {
            res.json(`error in finding item in database ,error info ${err}`);
        }

        else if(!info) 
        {
            console.log('user doesnot exist');
            let message='*please enter a valid username and password';
            res.json(message);
        }

        else{
            console.log(info);
            res.redirect('/');
        }
    });

}); 

This is the front end code

form.addEventListener('submit',(e)=>{
    e.preventDefault();
  
    const username=document.getElementById('username').value.trim();
    const password=document.getElementById('password').value;


    fetch('/login',{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        redirect:"manual",
        body:JSON.stringify({username,password})
    }).then((res)=>{
        if(res.redirected)
        {
            console.log(`redirected to ${res.url}`);
            window.location.href=res.url;
            // return;
        }
        else{
            console.log("no")
            return res.json()
        }
    })
    .then((data)=>{
        if(data)
        alt.innerText=data;//showing the error on the page
    })
    .catch((err)=>{throw err})
})

When I enter the correct credentials it prints the info on the console, that means it is inside the else and ideally should redirect back to the home page. But it never enters the if(res.redirected) statement which means it is returning false.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since some older chrome version does not read res.redirected, and for the sake of achieving cleaner codes as well as unexpected redirects (e.g. HTTP to HTTPS), you may want to set res.direct('/') to res.json({ redirect: '/' }) instead.

const results = await fetch(....).then(res.json());

if (results.redirect) {
     window.location.href = results.redirect
}

if (results.data) {
     //do something
}

Backend

if (info) {
   return res.json({ data: info });
} else {
   return res.json({ redirect: '/', error: true })
}
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