2017-07-14 46 views
0

我正在嘗試爲將來的HTTP請求添加包含令牌的'Authorization'頭文件。取回令牌似乎沒問題,但是當發出get請求時,它會失敗並顯示未經授權的錯誤消息。檢查請求頭Authorization頭後不請求塊存在......

window.crUtil = /*window.crUtil ||*/ (function() { 
 

 
    // Angular Services 
 
    var $injector = angular.injector(['ng']); 
 
    var $http = $injector.get('$http'); 
 

 

 
    // getting the CFF data 
 
    function get_data() { 
 
    \t \t getJWTAWS(); 
 
     var url = '/AWS/getDATA/555'; 
 
\t \t \t \t console.log('AUTH header before call: ' + $http.defaults.headers.common.Authorization); 
 
     $http.get(url,httpHeader).then(function successCallback(response) { 
 
      var data = response.data; 
 
      var cff = initCff(); 
 
      alert(data.itemId); 
 
      
 
     }, function errorCallback(response) { 
 
      initCff(); 
 
      alert("Error while getting data "); 
 
     }); 
 

 
    } 
 
\t \t 
 
    function getJWTAWS() { 
 
     var httpConfig = { 
 
      cache: true, 
 
      params: {} 
 
     }; 
 

 
     $http.get('/AWS/token', httpConfig).then(
 
      function(response) { 
 
       if (response.data.accessToken) { 
 
        // add jwt token to auth header for all requests made by the $http service 
 

 
        $http.defaults.headers.common.Authorization = response.data.tokenType + ' ' + response.data.accessToken; 
 
       } 
 
      }, 
 
      function(error) { 
 
       alert('jwt token could not be retrieved.'); 
 
      } 
 
     ); 
 
    } 
 

 

 
})(); 
 

 
var result = util.get_data(); 
 
console.log ('called search function ' + result);

功能爲gettoken()返回一個值,但我對這個主題是新我不能,如果十分確定我將標記添加到標題的方式是正確的。 您能否請您提供正確的方式在請求中包含標題。我也嘗試將其添加到獲取請求,如 $ http.get(URL,httpHeaders)... 但它也沒有工作。

回答

0

嘗試在配置塊中加入這一點,並設置令牌在rootscope

$httpProvider.interceptors.push({ 
    request: function (config) { 
     config.headers.Authorization = $rootScope.token; 
     return config; 
    } 
}) 
0

我不知道我完全理解你的問題,因爲你沒有提供你叫什麼

httpConfig

如果你正在努力申報頭,嘗試進行這樣的GET請求:

$http({ 
    method: 'GET', 
    url: YOUR_URL, 
    headers: { 
    'Content-Type': 'application/json', 
    'Authorization': AUTH_STRING_HERE 
    } 
}).then(function (response) { ... }); 

您可以在標題對象中添加任何標題。