簡體   English   中英

AngularJS在$ http.get中添加標題

[英]AngularJS Adding a header to the $http.get

我正在嘗試添加“授權”標頭,其中包含用於將來的HTTP請求的令牌。 檢索令牌似乎很好,但是在發出獲取請求時,它會失敗,並顯示未授權的錯誤消息。 在檢查請求標頭之后,請求標頭在請求塊中不存在...

 window.crUtil = /*window.crUtil ||*/ (function() { // Angular Services var $injector = angular.injector(['ng']); var $http = $injector.get('$http'); // getting the CFF data function get_data() { getJWTAWS(); var url = '/AWS/getDATA/555'; 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 "); }); } 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)之類的get請求中,但是它也沒有起作用。

我不確定您是否完全了解您的問題,因為您沒有提供您所說的內容

httpConfig

如果您在聲明標頭方面很費力,請嘗試發出以下get請求:

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

您可以在其中的標題對象中添加任何您喜歡的標題。

嘗試將其添加到配置塊中,並在rootscope中設置令牌

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM