Home > Back-end >  res.redirected returning false even when the backend returns a redirect
res.redirected returning false even when the backend returns a redirect

Time:02-10

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.

CodePudding user response:

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 })
}
  • Related