簡體   English   中英

響應頭存在於瀏覽器中但未由Angular $ http response.headers()解析

[英]Response header is present in browser but not parsed by Angular $http response.headers()

在我們的Angular應用程序中,我們需要解析一些$ http的響應頭。

特別是我們需要解析一些X-prefixed響應頭,例如X-Total-Results: 35

打開瀏覽器開發工具的Network選項卡並檢查相對於$ http請求的資源,我驗證了響應頭X-Total-Results: 35存在。

在瀏覽器中,X-Total-Results標頭可用,但無法在Angular $ http中解析。

有沒有辦法在$ http中訪問'raw'響應並為頭文件編寫自定義解析器?

$http.({method: 'GET', url: apiUrl,)
    .then( function(response){
        console.log('headers: ', response.headers());
        console.log('results header: ', response.headers('X-Total-Results'));
        // ...
    })

控制台輸出

headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}

results header: null

您無法在JavaScript上讀取標題但您可以在開發人員控制台上查看它的原因是因為對於CORS請求,您需要允許客戶端讀取標頭。

您的服務器需要發送此標頭:

Access-Control-Expose-Headers:X-Total-Results

要在評論中回答您的問題, Access-Control-Allow-Headers不允許根據W3規范使用通配符

使用$ httpProvider.interceptors可以攔截請求和響應

例如

$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
             return {
                 'responseError': function (response) {
                     console.log(response.config);
                 },
                 'response': function (response) {
                     console.log(response.config);
                 },
                 'request': function (response) {
                     console.log(response.config);
                 },
             };
         }]);

更新:您可以在通話中檢索標題信息

$http.({method: 'GET', url: apiUrl)
    .then( (data, status, headers, config){
        console.log('headers: ', config.headers);
        console.log('results header: ', config.headers('X-Total-Results'));
        // ...
    })

暫無
暫無

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

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