首先,我有带有 header 的 configAuth
,包括每个 Controller 上的 JWT token 。
var configAuth = {
headers: {
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token')
}
};
但是现在当我有大量的 Controller 时,我意识到我需要对此做点什么。我听说过拦截器
并尝试获取它们。
我知道我不能只为每个请求添加 token ,因为有些页面和请求(例如 /login
)根本不应该有 Authorization
token 。获取带有授权 header 的 html 文件在某种程度上给了我一个异常(exception)。所以我尝试像这样拆分请求:
angular.module('App')
.factory('sessionInjector',['$injector', function ($injector) {
var sessionInjector = {
request: function (config) {
if (config.url == "/one" || config.url == "/two"){
config.headers['Content-Type'] = 'application/json;charset=utf-8;';
config.headers['Authorization'] = localStorage.getItem('token');
} else {
config.headers['Content-Type'] = 'application/json;charset=utf-8;';
}
return config;
},
response: function(response) {
if (response.status === 401) {
var stateService = $injector.get('$state');
stateService.go('login');
}
return response || $q.when(response);
}
};
return sessionInjector;
}]);
但它不适用于像 /one/{one_id}
这样的请求,而且我无法对所有可能性进行硬编码。那么最佳实践是什么?
最佳答案
您现在拥有的是一个很好的起点。我假设您的大多数 API 都需要身份验证 token ,因此设置哪些端点不需要身份验证可能是更快的路径。我还没有测试过这个,但它可能会让你走上正轨。我将您的注入(inject)器设置为提供程序,以便您可以在配置中配置匿名路由规则。
angular.module('App')
.provider('sessionInjector',[function () {
var _anonymousRouteRules;
this.$get = ['$injector', getSessionInjector];
this.setupAnonymousRouteRules = setupAnonymousRouteRules;
function getSessionInjector($injector) {
var service = {
request: requestTransform,
response: responseTransform
};
function requestTransform(config) {
if (!isAnonymousRoute(config.url)){
config.headers['Authorization'] = localStorage.getItem('token');
}
config.headers['Content-Type'] = 'application/json;charset=utf-8;';
return config;
}
function responseTransform(response) {
if (response.status === 401) {
var stateService = $injector.get('$state');
stateService.go('login');
}
return response || $q.when(response);
}
return service;
}
function isAnonymousRoute(url) {
var isAnonymous = false;
angular.forEach(_anonymousRouteRules, function(rule) {
if(rule.test(url)) {
isAnonymous = true;
}
});
return isAnonymous;
}
function setupAnonymousRouteRules(anonymousRouteRules) {
_anonymousRouteRules = anonymousRouteRules;
}
}]);
有了这个,您可以通过传入网址的正则表达式数组来配置规则:
angular.module('App').config(['sessionInjectorProvider', config]);
function config(sessionInjectorProvider) {
sessionInjectorProvider.setupAnonymousRouteRules([
/.*\.html$/,
/^\/login$/
]);
}
关于javascript - 如何针对不同的请求(URL)拆分拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058070/