【发布时间】:2015-11-21 18:51:20
【问题描述】:
我正在使用带有 Express.js 的 Node 并尝试使用 JWT 进行身份验证,在用户登录后生成令牌并将其保存到本地存储,但是我不知道如何获取令牌进行身份验证。 这是我正在使用的代码:
登录视图:
$.ajax({
type: 'POST',
url: base_url + "login",
data: postData,
dataType: 'json',
success: function(data){
// console.log(data1);
// alert(data);
_(data);
if(data.success === false){
showError(data.msg);
}else{
showError(data.msg);
window.localStorage.setItem("authToken", data.token);
var token = window.localStorage.getItem('authToken');
if (token) {
$.ajaxSetup({
headers: {
'x-access-token': token
}
});
}
}
}
});
这是我在访问任何路由之前用来检查的路由身份验证:
router.use(function(req, res, next){
var token = req.headers['x-access-token'];
console.log(token);
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
}else{
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
在 console.log(token) 我得到一个 Undefined variable ,似乎我不知道如何从路由访问令牌。
非常感谢。
【问题讨论】:
-
您是否验证过(通过浏览器的开发者工具)实际发送了标头?
-
@mscdex 当我上网时,我看不到 x-access-token 作为请求标头或响应标头
-
您没有在对
$.ajax的调用中正确设置标题。查看这篇文章以了解如何设置标题 stackoverflow.com/questions/39947698/… - 您需要在传递给ajax函数的对象中使用headers字段,而不是在成功函数中。
标签: node.js express local-storage token jwt