2017-10-21 4 views
0

こんにちは私は外部APIを使用して現在のすべての通貨レートを収集したいと考えています。私のフロントはトークンに基づいており、トークンをlocalForageに格納していますが、これはasync localStorage以外のものです。例外を追加すると、angularJSのヘッダがデフォルトで設定されます

これは基本的に、すべてのバックエンド要求の前にトークンを含むヘッダーを追加します。

は、残念ながら、私は外部の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(つまり、カスタムロジックに基づいて)を使用して認証ヘッダーを設定できます。 – 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'); 
}); 
関連する問題