保存并从本地存储获取快速js令牌

即时通讯使用与Express.js的节点,并尝试使用JWT进行身份validation,用户login后生成一个令牌,并将其保存到本地存储,但我不知道如何获取身份validation的令牌。 这是即时通讯使用的代码:

login视图:

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

这是在访问任何路由之前使用检查的路由validation:

 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(令牌)我得到一个未定义的variables,似乎我不知道如何从路由访问令牌。 非常感谢。

“x-access-token”必须注册为允许的标题

 response.setHeader("Access-Control-Allow-Headers", "x-access-token, mytoken"); 

检查这篇文章: CORS和Access-Control-Allow-Headers是如何工作的?