use*_*406 9 token local-storage node.js express jwt
我使用Node与Express.js并尝试使用JWT进行身份验证,在用户登录后生成一个令牌,并将其保存到localstorage,但后来我不知道如何获取身份验证令牌.这是我正在使用的代码:
登录视图:
$.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
}
});
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
这是在访问任何路由之前用于检查的路由认证:
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.'
});
}
});
Run Code Online (Sandbox Code Playgroud)
在console.log(令牌)我得到一个未定义的变量,似乎我不知道如何从路由访问令牌.非常感谢.
小智 1
“x-access-token”必须注册为允许的标头
response.setHeader("Access-Control-Allow-Headers", "x-access-token, mytoken");
Run Code Online (Sandbox Code Playgroud)
查看这篇文章: CORS 和 Access-Control-Allow-Headers 如何工作?
| 归档时间: |
|
| 查看次数: |
4143 次 |
| 最近记录: |