Mis*_*Cat 6 jquery node.js jwt
我目前正在使用JSONWebtoken与NodeJS构建API.当我尝试使用标头中的令牌时,我收到错误403,它直接转到下面代码中的else语句,这意味着令牌根本就不存在.
以下是我在服务器端获取令牌的方法:
router.use(function(req, res, next){
var token = req.body.token || req.query.token || req.headers['x-access-token'];
//decode token
if(token) {
jwt.verify(token, app.get('secretKey'), function(err, decoded){
if(err)
return res.json({ success:false, message: 'failed, token problem'});
else {
req.decoded = decoded;
next();
}
});
}else {
return res.status(403).send({
success:false,
message: 'token not provided'
})
}
});
Run Code Online (Sandbox Code Playgroud)
在客户端,我正在使用JQuery并将其保存在cookie中:
令牌作为数据工作:
$.ajax({
type:'GET',
dataType: 'jsonp',
url :"http://localhost:3000/api/users",
data : {
token : $.cookie('token')
},
success: function(data, status) {
console.log("Status " + status);
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)令牌作为参数也有效
$.get("http://localhost:3000/api/users?token=" + $.cookie('token'))
.done(function(data){
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)这是问题,使用标题
$.ajax({
type:'GET',
url :"http://localhost:3000/api/users",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + $.cookie('token'));
},
success: function(data, status) {
console.log("Status " + status);
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)我还尝试在ajaxSetup上添加x-access-token作为头
$.ajaxSetup({
headers: {
'x-access-token': $.cookie('token')
}
});
Run Code Online (Sandbox Code Playgroud)
我一直得到403,这是令牌没有提供,我认为这是一个CORS问题所以我试图使用CORS npm包https://github.com/expressjs/cors不起作用,我试图实现这一点.
app.use(function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
Run Code Online (Sandbox Code Playgroud)
// 2016年8月22日更新信息
如果我在Safari中使用以下内容,它可以工作:
$.ajax({
type:'GET',
url :"http://localhost:3000/api/users",
headers : { "Authorization" : $.cookie('token') },
success: function(data, status) {
console.log("Status " + status);
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)
但有些如何与if和else语句一起使用,因此它响应下一个路由但也显示403消息.
我使用节点包更改我的 cors 设置
https://github.com/expressjs/cors
Run Code Online (Sandbox Code Playgroud)
到目前为止它可以通过使用它来工作
$.ajax({
type:'GET',
url :"http://localhost:3000/api/users",
headers: {'x-access-token': $.cookie('token')},
success: function(data, status) {
console.log("Status " + status);
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)