Angularjs - 匿名模板加载导致拦截器响应错误

时间:2015-08-26 01:10:59

标签: javascript angularjs

想检查,我正在使用带有AngularUI的AngularJS 1.4.4。最近我升级了我的网站以使用JWT令牌。 JWT令牌通过http请求中的标头发送。所以我还添加了一个拦截器来拦截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发出请求时,还有许多匿名模板请求被发送到我的网站中不存在的路由,导致整个程序停止工作。

enter image description here

如何删除/阻止/删除这些不必要的模板?

更新:如果发现这实际上是由AngularUI引导程序引起的。 enter image description 1 enter image description 2

我该怎样阻止拦截器拦截它?

1 个答案:

答案 0 :(得分:1)

您的错误很可能是由于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拦截器中有其他处理逻辑。