在重定向之前设置Express响应标头 [英] Set Express response headers before redirect
问题描述
我正在实施一个站点登录,它接收一个电子邮件/密码组合,检索一个API令牌,然后将其返回给用户,以便在localStorage中存储(加密)。
I'm implementing a site login that takes in an email/password combo, retrieves an API token, and returns it to the user to get stored (encrypted) in localStorage.
目前,在成功发布到 / login
后,应用程序会将用户重定向到索引页面,并带有令牌作为查询附加,如此(建议此处):
Currently, on successful POSTing to /login
, the app redirects the user to the index page, with the token attached as a query, like so (as suggested here):
login.post('/', function(req, res) {
...checking password...
Auth.getToken(user, function(err, token) {
res.redirect('/?token=' + token);
});
});
这样可行,但我希望尽可能保持网址清洁并设置令牌作为标题代替:
This works fine, but I'd prefer to keep my URLs as clean as possible and set the token as a header instead:
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
时,它没有出现:
console.log
-ing res._headers
shows that the headers are set as expected, but when I log req.headers
on the request to the index page, it's not showing up:
{ 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"' }
任何建议都赞赏!
推荐答案
设置标题在这里不起作用,因为重定向将执行新的http请求,您可以使用 express-session 存储身份验证令牌并在需要时获取
Setting headers wouldn't work here because a redirect will execute a new http request, you can use express-session to store the auth token and fetch it when you need it
req.session.accessToken = token
这篇关于在重定向之前设置Express响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!