Consuming JWT with jQuery, constantly getting error

I am currently creating an API using NodeJS using a JSONWebtoken. When I try to use the token in the header, I get a 403 error and it goes directly to the else statement in the code below, which means that the token is missing at all.

This is how I get the token on the server side:

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' }) } }); 

on the client side, I use jQuery and save it in a cookie:

  • as the data works:

     $.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); } }); 
  • how the parameter works too

     $.get("http://localhost:3000/api/users?token=" + $.cookie('token')) .done(function(data){ console.log(data); }); 
  • Here is the problem using the title

     $.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); } }); 

I also tried adding x-access-token as a header on ajaxSetup

 $.ajaxSetup({ headers: { 'x-access-token': $.cookie('token') } }); 

I keep getting 403, which is not a marker, I think this is a CORS problem, so I tried using the npm CORS package https://github.com/expressjs/cors does not work, I tried to implement this.

 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(); }); 

// update information on August 22, 2016

If I use the following in Safari, it works:

  $.ajax({ type:'GET', url :"http://localhost:3000/api/users", headers : { "Authorization" : $.cookie('token') }, success: function(data, status) { console.log("Status " + status); console.log(data); } }); 

But some of them relate to the if and else operator, so it responds to the next route, but also displays 403 message.

+6
source share
1 answer

i change cors configuration using node package

 https://github.com/expressjs/cors 

while it works using

 $.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); } }); 
0
source

All Articles