当我使用chrome扩展名为POSTMAN调用api
api.get('/me', function(req, res) {
res.json(req.decoded);
});
return api;
使用x-access-token作为一个有效的token值的报头,我得到一个有效的响应。
当使用从在线教程复制的拦截器时,我得到这个错误消息:
<http://localhost:3000/api/me 403 (Forbidden)
我的API/strong>
module.exports = function(app, express) {
api.use(function(req, res, next) {
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
if (token) {
jsonwebtoken.verify(token, secretKey, function(err, decoded) {
if (err) {
res.status(403).send({ sucess: false, message: "Failed to authenticate"});
} else {
req.decoded = decoded;
next();
}
});
} else {
res.status(403).send({ success: false, message: "No Token Provided"});
}
});
api.get('/me', function(req, res) {
res.json(req.decoded);
});
return api;
}
My Authentication Service
.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};
authFactory.getUser = function() {
if(AuthToken.getToken())
///Here it breaks here
return $http.get('/api/me');
else
return $q.reject({ message: "User has no fucking token"});
}
return authFactory;
})
.factory('AuthToken', function($window) {
var authTokenFactory = {};
authTokenFactory.getToken = function() {
return $window.localStorage.getItem('token');
}
authTokenFactory.setToken = function(token) {
if (token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
}
return authTokenFactory;
})
.factory('AuthInterceptor', function($q, $location, AuthToken) {
var interceptorFactory = {};
interceptorFactory.request = function(config) {
var token = AuthToken.getToken();
if(token) {
config.header['x-access-token'] = token;
}
return config;
};
interceptorFactory.responeError = function(response) {
if (response.status == 403)
$location.path('/login');
return $q.reject(response);
}
return interceptorFactory; })
.factory('Auth', function($http, $q, AuthToken) {
var authFactory = {};
authFactory.getUser = function() {
if(AuthToken.getToken())
return $http.get('/api/me');
else
return $q.reject({ message: "User has no fucking token"});
}
return authFactory; })
你必须确保拦截器是有效的,通过将它添加到$httpProvider。下面的代码在应用的配置中做到了这一点:
.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
提醒一下,你有一个拼写错误:
interceptorFactory.responeError -> interceptorFactory.responseError
编辑:
另外,当你想要对多个请求执行相同的行为而不需要修改每个请求时,拥有拦截器会有所帮助。对于这个用例,也许不使用拦截器更简单,而是为一个请求手动添加头文件:
return $http.get('/api/me', { headers: {'x-access-token': AuthToken.getToken()} });