如何从fetch中获取响应的标头 [英] How to get headers of the response from fetch
问题描述
我在chrome版本52.0.2743.82(64位)上使用fetch。我想获得响应中的所有标题。以下代码段仅返回 content-type
但如果您查看chrome dev工具,则会显示许多其他响应标头。如何从fetch中获取其他标题。
I am using fetch on chrome Version 52.0.2743.82 (64-bit). I want to get all the headers in the response. Following snippet only return content-type
but if you peek into chrome dev tools it shows many other response headers. How to get other headers from fetch.
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实现。仍然没有运气。
I tried polyfilling(manually overriding) the github implementation. Still no luck.
推荐答案
通过ajax请求跨域内容时,无法访问所有标头。如果来源相同,您可以访问所有标题。
You can't access all the headers when requesting cross-domain content via ajax. You can access all headers if origin is same.
如W3规范中所述这里,只有 Content-Type
,最后修改
, Content-Language
, Cache-Control
, Expires
, Pragma
标题可以访问。
As explained in W3 Specifications here, only Content-Type
, Last-modified
, Content-Language
, Cache-Control
, Expires
, Pragma
headers are accessible.
进一步 https://httpbin.org/get
只从可访问标题列表中发送 Content-Type
标题,所以,你只能得到它。
Further https://httpbin.org/get
send only Content-Type
header from list of accessible headers so, you got that only.
编辑:您可以通过发送 Access-Control-Expose-Headers
,其中包含您希望客户在响应中访问的标头。
You can expose non-standard CORS response headers by sending Access-Control-Expose-Headers
with the headers you want the client to access on the response.
这篇关于如何从fetch中获取响应的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!