【问题标题】:Cannot set headers after they are sent to the client with expressjs使用 expressjs 将标头发送到客户端后无法设置标头
【发布时间】:2019-08-10 12:57:46
【问题描述】:

我想在成功登录后重定向到另一个页面,但它向我显示了这条消息“在将标头发送到客户端后无法设置标头”,我知道我应该将 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'})
            }


        }
    }
    )
})

【问题讨论】:

  • 可能是重定向前的res.send(token) 这一行。也许还有另一种方法可以做到这一点?之后可以这样做吗?

标签: javascript express


【解决方案1】:

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

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

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

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';

【讨论】:

  • 谢谢你!!!!它现在工作,我使用了第二个选项,同时我想将它存储在本地存储中的令牌
  • 您可能需要考虑使用document.cookie - 此值会自动附加到您的请求中,并且可以被服务器读取。
  • 谢谢你!!!我无法真诚地表达我现在的快乐,谢谢你的帮助,看到人们互相帮助很高兴
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2021-11-30
  • 2021-06-18
  • 2022-01-14
  • 2021-04-07
  • 1970-01-01
相关资源
最近更新 更多