Javascript 使用 Fetch API 读取响应头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43344819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading response headers with Fetch API
提问by jules
I'm in a Google Chrome extension with permissions for "*://*/*"and I'm trying to make the switch from XMLHttpRequest to the Fetch API.
我在 Google Chrome 扩展程序中,有权限"*://*/*",我正在尝试从 XMLHttpRequest 切换到Fetch API。
The extension stores user-input login data that used to be put directly into the XHR's open() call for HTTP Auth, but under Fetch can no longer be used directly as a parameter. For HTTP Basic Auth, circumventing this limitation is trivial, as you can manually set an Authorization header:
该扩展存储用户输入的登录数据,以前直接放入 XHR 的 open() 调用进行 HTTP 身份验证,但在 Fetch 下不能再直接用作参数。对于 HTTP 基本身份验证,绕过此限制是微不足道的,因为您可以手动设置授权标头:
fetch(url, {
headers: new Headers({ 'Authorization': 'Basic ' + btoa(login + ':' + pass) })
} });
HTTP Digest Authhowever requires more interactivity; you need to read parameters that the server sends you with its 401 response to craft a valid authorization token. I've tried reading the WWW-Authenticateresponse header field with this snippet:
然而,HTTP Digest Auth需要更多的交互性;您需要读取服务器通过 401 响应发送给您的参数以制作有效的授权令牌。我试过WWW-Authenticate用这个片段读取响应头字段:
fetch(url).then(function(resp) {
resp.headers.forEach(function(val, key) { console.log(key + ' -> ' + val); });
}
But all I get is this output:
但我得到的只是这个输出:
content-type -> text/html; charset=iso-8859-1
Which by itself is correct, but that's still missing around 6 more fields according to Chrome's Developer Tools. If I use resp.headers.get("WWW-Authenticate")(or any of the other fields for that matter), i get only null.
这本身是正确的,但根据 Chrome 的开发人员工具,仍然缺少大约 6 个字段。如果我使用resp.headers.get("WWW-Authenticate")(或与此相关的任何其他字段),我只会得到null.
Any chance of getting to those other fields using the Fetch API?
有机会使用 Fetch API 访问其他字段吗?
回答by Rajbir Jawanda
There is a restriction to access response headers when you are using Fetch API over CORS. Due to this restriction, you can access only following standard headers:
当您通过 CORS 使用 Fetch API 时,访问响应标头存在限制。由于此限制,您只能访问以下标准标头:
Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma
Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma
When you are writing code for Google Chrome extension, you are using CORS, hence you can't access all headers. If you control the server, you can return custom information in the response bodyinstead of headers
当您为 Google Chrome 扩展编写代码时,您使用的是CORS,因此您无法访问所有标头。如果您控制服务器,则可以在响应中返回自定义信息body而不是headers
More info on this restriction - https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
有关此限制的更多信息 - https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
回答by Avram Tudor
From MDN
来自MDN
You can also get all the headers by accessing the entries Iterator.
您还可以通过访问条目 Iterator 来获取所有标头。
// Display the key/value pairs
for (var pair of res.headers.entries()) {
console.log(pair[0]+ ': '+ pair[1]);
}
Also, keep in mind thispart:
另外,请记住这一部分:
For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.
出于安全原因,某些标头只能由用户代理控制。这些头包括禁止头名称和禁止响应头名称。
回答by Nitin Jadhav
If it's NOT CORS:
如果不是 CORS:
Fetch does not show headers while debugging or if you console.logresponse.
Fetch 在调试或console.log响应时不显示标题。
You have to use following way to access headers.
您必须使用以下方式访问标题。
response.headers.get('x-auth-token')
回答by J?rn Andre Sundt
For backward compatibility with browsers that do not support ES2015 iterators (and probably also need fetch/Promise polyfills), the Headers.forEachfunction is the best option:
为了与不支持 ES2015 迭代器(并且可能还需要 fetch/Promise polyfills)的浏览器向后兼容,Headers.forEach函数是最好的选择:
r.headers.forEach(function(value, name) {
console(name + ": " + value);
});
Tested in IE11 with Bluebird as Promise polyfill and whatwg-fetch as fetch polyfill. Headers.entries(), Headers.keys() and Headers.values() does not work.
在 IE11 中使用 Bluebird 作为 Promise polyfill 和 whatwg-fetch 作为 fetch polyfill 进行了测试。Headers.entries()、Headers.keys() 和 Headers.values() 不起作用。
回答by Sheng
For us to fix this restriction issue, adding exposed header names is good enough.
为了解决这个限制问题,添加公开的头名称就足够了。
access-control-expose-headers: headername1, headername2, ...
access-control-expose-headers: headername1, headername2, ...
After setting this header, the client side script is able to read those headers (headername1, headername2, ...) from the response.
设置此标头后,客户端脚本能够从响应中读取这些标头(headername1、headername2...)。

