如何从 fetch 中获取响应的标头
我在 chrome 版本 52.0.2743.82(64 位)上使用 fetch.我想获取响应中的所有标题.以下代码段仅返回 content-type
但如果您查看 chrome 开发工具,它会显示许多其他响应标头.如何从 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();
}
})
我尝试对 github 实现进行 polyfill(手动覆盖).还是没有运气.
I tried polyfilling(manually overriding) the github implementation. Still no luck.
推荐答案
通过ajax请求跨域内容时,无法访问所有header.如果来源相同,您可以访问所有标题.
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
、Last-modified
、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.
相关文章