2015-03-02 162 views
26

我的服務器返回的這種標題的:Content-Range:0-10/0如何在angularjs中讀取響應頭?

enter image description here

我試過的角度看這個頭,沒有運氣:

var promise = $http.get(url, { 
    params: query 
}).then(function(response) { 
    console.log(response.headers()); 
    return response.data; 
}); 

剛剛打印

Object {content-type: "application/json; charset=utf-8"} 

任何想法如何訪問內容範圍標題?

回答

30

使用的成功和錯誤回調

From documentationheaders變量。

$http.get('/someUrl'). 
    success(function(data, status, headers, config) { 
    // this callback will be called asynchronously 
    // when the response is available 
    }) 
    .error(function(data, status, headers, config) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 

如果您位於同一個域中,則應該能夠檢索迴應頭。如果跨域,則需要在服務器上添加Access-Control-Expose-Headers標頭。

Access-Control-Expose-Headers: content-type, cache, ... 
+0

這仍然沒有給我響應頭,只是請求頭。 – 2015-03-02 08:48:56

+0

更新了答案。 – 2015-03-02 08:52:16

+0

我已經啓用跨網域。我的問題中的屏幕截圖顯示,內容範圍標題位於chrome檢查器中的響應中。所以服務器不是問題。 – 2015-03-02 08:57:14

9

基於穆罕默德的答案更新中...

$http.get('/someUrl'). 
    success(function(data, status, headers, config) { 
    // this callback will be called asynchronously 
    // when the response is available 
    console.log(headers()['Content-Range']); 
    }) 
    .error(function(data, status, headers, config) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 
22

爲什麼不乾脆試試這個:

var promise = $http.get(url, { 
    params: query 
}).then(function(response) { 
    console.log('Content-Range: ' + response.headers('Content-Range')); 
    return response.data; 
}); 

特別是如果你想要回promise所以它可能是一部分一個承諾鏈。

+2

給出一個(+1),因爲'response'有一個'headers'參數的'headers()'方法。雖然這是我的問題;我無法通過'response.headers('Authorization')'檢索'Authorization'頭文件[或任何其他文件],即使我可以在明顯的地方看到response.config.headers ['Authorization']!這個功能是什麼,然後呢? – Cody 2016-06-10 04:12:50

+0

這是一個跨域請求嗎? – 2016-06-13 21:02:13

+0

你可能不應該在這樣的單個請求中使用A uthorization。使用攔截器授權的東西 – 2016-08-16 08:20:56

5

此外尤金Retunsky的答案,從關於響應$http文檔引用:

響應對象具有以下屬性:

  • 數據 - {string|Object} - 響應體與轉化轉換功能。

  • status - {number} - 響應的HTTP狀態碼。

  • 標頭 - {function([headerName])} - 標頭吸氣功能。

  • config - {Object} - 用於生成請求的配置對象。

  • statusText - {string} - 響應的HTTP狀態文本。

請注意參數回調整理的$resource(V1。6)是不一樣的如上:

成功回調調用與(value (Object|Array), responseHeaders (Function), status (number), statusText (string))參數,其中值是所填充的資源實例或集合對象。使用(httpResponse)參數調用錯誤回調。

0

Cors情況下的響應標題保持隱藏狀態。 您需要添加回應標題以指示Angular向JavaScript公開標題。

// From server response headers : 
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
header("Access-Control-Allow-Headers: Origin, X-Requested-With, 
Content-Type, Accept, Authorization, X-Custom-header"); 
header("Access-Control-Expose-Headers: X-Custom-header"); 
header("X-Custom-header: $some data"); 

var data = res.headers.get('X-Custom-header'); 

來源:https://github.com/angular/angular/issues/5237

相關問題