【问题标题】:Set Express response headers before redirect在重定向之前设置 Express 响应标头
【发布时间】:2015-11-21 00:19:02
【问题描述】:

我正在实现一个站点登录,它接收电子邮件/密码组合,检索 API 令牌,并将其返回给用户以存储(加密)在 localStorage 中。

目前,在成功发布到/login 后,应用程序会将用户重定向到索引页面,并将令牌作为查询附加,如下所示(建议here):

login.post('/', function(req, res) {
    ...checking password...

    Auth.getToken(user, function(err, token) {
        res.redirect('/?token=' + token);
    });
});

这很好用,但我希望尽可能保持我的 URL 干净,并将令牌设置为标头:

login.post('/', function(req, res) {
    ...checking password...

    Auth.getToken(user, function(err, token) {
        res.set('x-access-token', token);
        console.log(res._headers);
            // --> {'x-powered-by': 'Express', 'x-access-token': <token>}
        res.redirect('/');
    });
});

console.log-ing res._headers 表明标头已按预期设置,但是当我在对索引页面的请求中记录req.headers 时,它没有显示:

{ host: 'localhost:3000',
  connection: 'keep-alive',
 'cache-control': 'max-age=0',
 accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
 'upgrade-insecure-requests': '1',
 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
 referer: 'http://localhost:3000/login',
 'accept-encoding': 'gzip, deflate, sdch',
 'accept-language': 'en-US,en;q=0.8',
 cookie: 'ifusr=crwj; _ga=GA1.1.1933420201.1409901705',
 'if-none-match': '"1195161647"' }

任何建议表示赞赏!

【问题讨论】:

    标签: node.js express routing http-headers


    【解决方案1】:

    在此处设置标头不起作用,因为重定向将执行新的 http 请求,您可以使用 express-session 存储身份验证令牌并在需要时获取它

    req.session.accessToken = token
    

    【讨论】:

    • 所以如果我不想使用会话,查询字符串几乎是我将上下文传递给新请求的唯一选择?
    • 您可以使用res.render('index'),但不确定是否需要在路由中触发某些内容,如果需要,查询字符串是您唯一的选择
    • 如果您展示了如何将 accessToken 放入会话中...?
    • 额外的双升船让您在res.render('index')@JuliánDuque 中展示如何操作
    猜你喜欢
    • 2018-11-26
    • 2014-11-30
    • 2015-11-28
    • 1970-01-01
    • 2020-12-20
    • 2022-10-07
    • 2012-07-13
    • 2019-07-19
    • 2013-01-07
    相关资源
    最近更新 更多