在angularJS中添加例外默认值标头

时间:2017-10-21 21:51:40

标签: angularjs http http-headers token

您好我想使用外部API来收集所有当前货币汇率。我的前端基于令牌,我将令牌存储在localForage中,这只是异步localStorage。

//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下载所有当前货币汇率时,我收到以下错误:

  

请求标头字段预检响应中的Access-Control-Allow-Headers不允许授权。

这是因为我用我的令牌添加了标题。我可以在设置$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;时以某种方式添加例外吗?

1 个答案:

答案 0 :(得分: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');
});