想检查一下,我正在使用 AngularJS 1.4.4 和 AngularUI 。所以最近我升级了我的网站以使用 JWT token 。 JWT token 通过 http 请求中的 header 发送。所以我还添加了一个拦截器来拦截 Angular 向服务器发出的所有请求,如下所示
request: function(config){
config.headers = config.headers || {};
if ($localStorage.jwtToken) {
config.headers.Authorization = 'Bearer ' + $localStorage.jwtToken;
}
return config;
},
response: function(response) {
if(response.headers('New-Jwt-Token')){
console.log(response.headers('New-Jwt-Token'));
}
},
responseError: function (response) {
// handle the case where the user is not authenticated
if (response.status === 401) {
if(response.data.error === 'token_ttl_expired'){
if(response.data.new_jwt_token){
$localStorage['jwtToken'] = response.data.new_jwt_token;
console.log('jwt updated');
}
}
}
return $q.reject(response);
}
我注意到,当 Angular 发出请求时,还会向我的网站中不存在的路由发出许多匿名模板请求,这会导致整个程序停止工作。
我应该如何删除/阻止/删除这些不必要的模板加载?
更新:如果发现这实际上是由 AngularUI Bootstrap 引起的。
我应该如何防止它被拦截器拦截?
最佳答案
您的错误很可能是由于您的 response
拦截器中没有返回 response
造成的。所以应该是:
response: function(response) {
if(response.headers('New-Jwt-Token')){
console.log(response.headers('New-Jwt-Token'));
}
return response;
},
request
拦截器将拦截所有请求 AFAIK。请注意,使用 ui-bootstrap,模板会缓存在 $templateCache
中,因此实际上不会将任何 GET
发送到您的服务器。
这是完全没有必要的,但是如果在 $templateCache
中找到,您可以在请求拦截器中执行的操作是不执行任何操作。
request: function(config){
if (config.url && $templateCache.get(config.url)) {
// Don't do anything
return config;
}
config.headers = config.headers || {};
if ($localStorage.jwtToken) {
config.headers.Authorization = 'Bearer ' + $localStorage.jwtToken;
}
return config;
},
再说一次,这不是必需的,也没有多大作用,但我把它放在这里,以防 request
拦截器中有其他处理逻辑。
关于javascript - Angularjs - 匿名模板加载导致拦截器中的响应错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216467/