使用 Fetch API 读取响应头 [英] Reading response headers with Fetch API

查看:147
本文介绍了使用 Fetch API 读取响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Google Chrome 扩展程序中,具有 "*://*/*" 权限,我正在尝试从 XMLHttpRequest 切换到 Fetch API.

I'm in a Google Chrome extension with permissions for "*://*/*" and I'm trying to make the switch from XMLHttpRequest to the Fetch API.

该扩展存储用户输入的登录数据,以前直接放入 XHR 的 open() 调用进行 HTTP Auth,但在 Fetch 下不能再直接用作参数.对于 HTTP 基本身份验证,绕过此限制是微不足道的,因为您可以手动设置授权标头:

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:

fetch(url, {
  headers: new Headers({ 'Authorization': 'Basic ' + btoa(login + ':' + pass) })
  } });

HTTP Digest Auth 但是需要更多的交互性;您需要读取服务器通过 401 响应发送给您的参数以制作有效的授权令牌.我尝试使用以下代码段读取 WWW-Authenticate 响应标头字段:

HTTP Digest Auth however 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-Authenticate response header field with this snippet:

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

这本身是正确的,但根据 Chrome 的开发者工具,仍然缺少大约 6 个字段.如果我使用 resp.headers.get("WWW-Authenticate")(或与此相关的任何其他字段),我只会得到 null.

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.

是否有机会使用 Fetch API 访问其他字段?

Any chance of getting to those other fields using the Fetch API?

推荐答案

当您通过 CORS 使用 Fetch API 时,访问响应标头存在限制.由于此限制,您只能访问以下标准标题:

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:

  • 缓存控制
  • 内容语言
  • 内容类型
  • 过期
  • 上次修改
  • Pragma

当您为 Google Chrome 扩展编写代码时,您使用的是 CORS,因此您无法访问所有标题.如果你控制服务器,你可以在响应中返回自定义信息 body 而不是 headers

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 body instead of headers

有关此限制的更多信息 - https://developer.google.com/web/updates/2015/03/introduction-to-fetch#response_types

More info on this restriction - https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types

这篇关于使用 Fetch API 读取响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆