【发布时间】:2017-04-12 02:53:15
【问题描述】:
我已经编写了一个身份验证拦截器,它将身份验证令牌添加到请求中,并在用户未登录时处理身份验证错误。
var storeApp = angular.module('storeApp');
storeApp.factory('authInterceptor', function ($q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response.status === 401 || response.data.error === 'token_not_provided') {
console.log('auth error');
}
return $q.reject(response);
}
};
});
storeApp.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('authInterceptor');
});
问题是身份验证拦截器被添加到每个请求中,无论请求是否需要身份验证。创建仅在路由需要身份验证时拦截的身份验证拦截器的最佳方法是什么?
【问题讨论】:
标签: angularjs