2017-10-21 3 views
0

안녕하세요, 외부 API를 사용하여 모든 현재 환율을 수집하고 싶습니다. 내 프론트는 토큰을 기반으로하고 localForage에 토큰을 저장하고 있는데 이것은 async 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-interceptor를 작성하고 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'); 
}); 
관련 문제