使用express.js将标头发送到客户端后无法设置标头

时间:2019-03-19 21:48:20

标签: javascript express

成功登录后,我想重定向到另一个页面,但它向我显示此消息“将标头发送到客户端后无法设置标头”,我知道我应该将res.redirect放置在其他位置,但我真的很努力这个

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 个答案:

答案 0 :(得分:1)

res.redirect只是一个糖,用于将重定向状态设置为302并添加一个Location标头。您可能只需将其更改为:

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

res.send(token)真的是您想做的事情吗?在我看来,您似乎想在Set-Cookie响应中附加一个/login标头。所以也许您可以这样做:

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

或者您的服务器根本不应该处理重定向?如果您要将令牌发送回客户端,也许您的客户端负责将令牌附加到您的document cookie,然后执行客户端重定向?

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

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