2017-10-21 119 views
0

您好,我希望使用外部API来收集所有当前的货币汇率。我的前面是基于令牌的,我在localForage中存储了令牌,它只是异步localStorage。在angularJS中添加一个例外默认头文件

//this execute after every page refresh 
$localForage.getItem('authorization') 
    .then(function(authData) { 
     if(authData) { 
      $scope.authentication.isAuth = true; 
      $http.defaults.headers.common.Authorization = 'Bearer ' + authData.token; 
      //set authentication variable to true and add token to every request after page refresh 
     } 
    }, function(){ 
      console.log("error with getting authorization localForage after refresh"); 
     } 
    ); 


//this execute after custom event emitted after success login response 
$rootScope.$on('localForageUpdated', function(event){ 
    $localForage.getItem('authorization') 
     .then(function(authData) { 
      if(authData) { 
       $http.defaults.headers.common.Authorization = 'Bearer ' + authData.token; 
       $scope.authentication.isAuth = true; 
       //set authentication variable to true and add token to every request after page refresh 
      } else { 
       $scope.authentication.isAuth = false; 
      } 
     }, function(){ 
       console.log("error with getting authorization localForage on event"); 
      } 
     ); 
}); 

因此,这基本上是在每个后​​端请求之前添加包含标记的标头。

不幸的是,当我尝试从外部API下载所有当前的汇率我获得以下错误:

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

这是由于事实上我说头与我的令牌。我可以在注册$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;时以某种方式添加异常吗?

+0

您可以编写一个http拦截器并使用if-else设置auth头文件(即基于某些自定义逻辑) – harishr

回答

1

这是我的解决方案,你可以用它来激励你。

我创建au拦截器来添加授权。在这个拦截中,你可以把你的异常逻辑基于你的需要,在我的情况下,我将其基于URL。

angular.module('yourAppName').factory('authInterceptor', function ($q, $window) { 
    return { 
     request: function (config) { 
      config.headers = config.headers || {}; 

      if ($window.localStorage.token 
        && $window.localStorage.token !== undefined 
        && $window.localStorage.token !== 'undefined') { 
       if(config.url.startsWith("xyz")){ 
        delete config.headers.Authorization; 
       } else { 
        config.headers.Authorization = 'Bearer ' + $window.localStorage.token; 
       } 
      } 
      return config; 
     }, 
     response: function (response) { 
      return response || $q.when(response); 
     }, 
     // optional method 
     responseError: function (response) { 
      return $q.reject(response); 
     } 
    }; 
}); 

angular.module('rmsApp').config(function ($httpProvider) { 
    $httpProvider.interceptors.push('authInterceptor'); 
}); 
相关问题