0
votes

I want to redirect to another page after successful login , but it show me this message "Cannot set headers after they are sent to the client", i know i should have place the res.redirect somewhere else but i really struggling with this one

router.get('/login',(req,res)=>{
    res.render('login')
})
router.post('/login',(req,res)=>{
    user.findOne({
        where: {
            userName : req.body.userName
        }
    })
    .then(userInfo=>{
        if(userInfo){
            if(bcrypt.compareSync(req.body.password,userInfo.password)){
                const token = jwt.sign(userInfo.dataValues,process.env.SECRET_KEY,{
                    expiresIn:1440
                })

               res.send(token)
               res.redirect('/home')

            }

            else {
                res.status(400).json({error:'user doesnt exist'})
            }


        }
    }
    )
})
1
Could be this line res.send(token) before the redirect. Maybe there's another way to do this? Is it possible to do this after? - user10957435

1 Answers

1
votes

res.redirect is just sugar for setting the a redirect status to 302 and adding a Location header. You could probably just change this to:

res.setHeader('Location', '/home');
res.send(token);

Is res.send(token) really what you want to be doing? Seems to me like you'd want to be attaching a Set-Cookie header in the /login response. So maybe instead you do:

res.setHeader('Set-Cookie', `token=${token}`);
res.redirect('/home');

Or maybe your server should not be handling the redirect at all? If you're sending the token back to the client, maybe your client is responsible for attaching the token to your document cookie, and then performing the redirect client-side?

/* This code is run in the browser after you receive the token, not the server */

document.cookie = `token=${token}`;
window.location.href = '/home';