我正在学习本教程: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');对/restricted的请求:
$http({url: '/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
console.log(data.name); // Should log 'foo'
});我的代码和教程代码之间唯一明显的区别是我使用的是localStorage而不是sessionStorage。
发布于 2014-08-19 18:58:33
我问,我回答。
在创建此行的令牌时:
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
};我不知道这会是个问题。
https://stackoverflow.com/questions/25387529
复制相似问题