当我使用名为POSTMAN的chrome扩展名来调用api
时api.get('/me', function(req, res) {
res.json(req.decoded);
});
return api;
使用x-access-token作为具有有效标记值的标头,我得到有效的响应。
当使用从在线教程中复制的拦截器时,我收到以下错误消息:
http://localhost:3000/api/me 403(禁止)
我的API
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;
}
我的身份验证服务
.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; })
答案 0 :(得分:2)
您必须通过将拦截器添加到$ httpProvider来确保拦截器生效。以下代码在app的配置中执行此操作:
.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
作为一个单挑,你有拼写错误:
interceptorFactory.responeError -> interceptorFactory.responseError
编辑:
此外,如果您希望多个请求具有相同的行为而不必更改每个请求,那么使用拦截器会有所帮助。对于这个用例,也许更简单的是不使用拦截器,而是手动为一个请求添加头:
return $http.get('/api/me', { headers: {'x-access-token': AuthToken.getToken()} });