【发布时间】:2019-04-22 06:25:37
【问题描述】:
我想根据用户请求呈现一个新的 HTML 页面,该页面只有在 authorization 标头设置正确的情况下才能访问。我最初以为浏览器会重定向到该页面,但发现并非如此。我找到了一些方法来处理这个问题,例如替换 DOM,但我认为这不是一个好的解决方案。
这是来自 UI 的 fetch 调用,它返回 HTML,但当前不呈现它:
fetch('/protected_route', {
headers: {
'authorization': 'Bearer ' + sessionStorage.getItem('token')
}
}).then(response => {
// What to do with the response
});
这是服务器代码,如果有帮助的话:
app.get('/protected_route', (req, res) => {
const bearer = req.headers['authorization'];
if(typeof bearer === 'undefined') {
res.json({message: 'Not logged in'});
}
else {
const token = bearer.split(' ')[1];
jwt.verify(token, config.secret, (error, data) => {
if(error) {
res.json({message: 'Error verifying token'});
}
else {
res.render('protected_route');
}
});
}
});
【问题讨论】:
-
fetch运行 HTTP 请求,但它旨在与服务器通信 不离开当前页面。既然您是手动处理授权,为什么不使用 cookie 来代替呢?这样您就可以在/protected_route处理程序中检查 cookie,然后只需使用<a>让用户移动到页面。 -
@ChrisG 感谢您的回答!我实际上没有考虑过这个选项。我刚刚用
window.location.href=path重定向了用户,它现在可以工作了。
标签: javascript html node.js express fetch