我正在关注本教程:https ://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
当从前端向 /restricted 发出 http 请求时,我在 cmd 中收到此错误:
SyntaxError: Unexpected token m
at Object.parse (native)
at Object.jwsDecode [as decode]
等等。
我将展示我的代码的简化版本。
节点JS:
登录功能,以令牌响应:
app.post('/login', function (req, res) {
var token = jwt.sign(email, secret, expires);
res.json({ token: token });
});
限制访问的设置等。
var application_root = __dirname,
express = require("express"),
expressJwt = require('express-jwt'),
jwt = require('jsonwebtoken');
var app = express();
app.use(express.json());
app.use(express.urlencoded());
var secret = '9mDj34SNv86ud9Ns';
// We are going to protect /api routes with JWT
app.use('/restricted', expressJwt({secret: secret}));
app.get('/restricted', function (req, res) { console.log('fuck'); });
AngularJS:
请求拦截器:
app.factory('httpRequestInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.localStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
console.log('Bearer ' + $window.localStorage.token);
}
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authenticated
}
return response || $q.when(response);
}
};
});
推送拦截器的配置:
$httpProvider.interceptors.push('httpRequestInterceptor');
对 /restricted 的 HTTP 请求:
$http({url: '/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
console.log(data.name); // Should log 'foo'
});
我的代码和教程代码之间唯一明显的区别是我使用的是 localStorage 而不是 sessionStorage。