我正在学习本教程: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]
等等。
我将展示我的代码的简化版本。
的NodeJS:
登录功能,使用令牌响应:
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');
HTTP请求/限制:
$http({url: '/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
console.log(data.name); // Should log 'foo'
});
我的代码和教程代码之间唯一可见的区别是我使用localStorage而不是sessionStorage。
答案 0 :(得分:2)
我问,我回答。
在此行上创建令牌:
var token = jwt.sign(email, secret, expires);
我使用的是电子邮件,这只是一个常规变量。
var email = req.body.email;
但是,expressJwt需要一个JSON:
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: 123
};
我不知道这可能是个问题。