2016-08-15 93 views
12

我在使用chrome 52.0.2743.82(64位)進行提取。我想獲得響應中的所有標題。以下片段僅返回content-type,但如果您瀏覽chrome開發工具,則會顯示許多其他響應標頭。如何獲取其他標題。如何從提取中獲取響應的標題

fetch('https://httpbin.org/get') 
    .then(response => { 
     const headers = response.headers.entries(); 
     let header = headers.next(); 
     while (!header.done){ 
     console.log(headers.value); 
     header = header.next(); 
     } 
    }) 

我嘗試了polyfilling(手動覆蓋)github實現。仍然沒有運氣。

+2

如果你知道你正在尋找什麼頭,你可以嘗試response.headers.get('header-name') – KumarM

+0

看看這個頁面底部的兼容性表,它並沒有說鉻支持條目()然而。 https://developer.mozilla.org/en-US/docs/Web/API/Headers – KumarM

回答

26

當通過ajax請求跨域內容時,您無法訪問所有標題。如果來源相同,您可以訪問所有標題。

如W3規格here,只有Content-TypeLast-modifiedContent-LanguageCache-ControlExpires解釋,Pragma頭都可以訪問。

更多https://httpbin.org/get只發送Content-Type從可訪問標題列表頭,所以,你只有這一點。

編輯:您可以通過發送Access-Control-Expose-Headers您希望客戶端在響應中訪問的標頭來暴露非標準CORS響應標頭。

+0

這非常有幫助。對於那些Rails 5開發者,編輯'config/initializers/cors.rb'工作。我在'resource'*''聲明中加入:'expose:['Location']' – jasonseminara