처음에는 컨트롤러마다 JWT 토큰을 포함하여 configAuth
개의 헤더가 있습니다.다른 요청 (URL)에 대한 인터셉터를 분할하는 방법은 무엇입니까?
var configAuth = {
headers: {
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token')
}
};
하지만 지금은 컨트롤러가 아주 많을 때 나는 그것에 대해 뭔가를해야한다는 것을 깨달았습니다. 나는 interceptors
에 대해 들었고 그들을 얻으려고 노력했다.
/login
과 같은 일부 페이지 및 요청은 토큰이 전혀 없기 때문에 모든 요청에 토큰을 넣을 수 없다는 것을 알고 있습니다. Authorization header
으로 html 파일을 가져 오는 것은 어떻게 든 예외를 제공합니다.
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}
같은 요청을 작동하지 않습니다와 나는 모든 가능성을 하드 코딩 할 수 없습니다 그래서 그런 요청을 분할 시도했습니다. 그래서 이것에 대한 가장 좋은 방법은 무엇입니까?
여기에 모범 사례로가는 아니,하지만 당신은 쉽게 '보다 더 유연한 매처 (matcher)를 사용할 수 있습니다 config.url == "/ one"'. 예를 들어, url *이'/ config.url.indexOf ('/ one') === 0' 또는 regex를 사용하여 "/ one"으로 시작하는지 확인할 수 있습니다. 또한 권한이 필요한 것보다 많은 라우트가있는 경우에는'if (config.url! == '/ login')'와 같이 다른 방법으로 체크를 돌릴 수 있습니다. – noppa