ES6:从 CORS 获取调用中检索响应标头

Ger*_*erb 4 javascript fetch cors ecmascript-6

我有一个使用 ES6 fetch API 的 React 应用程序来使用 CORS 调用休息端点。提取调用工作得很好,但我无法获取从服务器发送的响应标头。我可以在 Chrome 开发工具中看到响应标头,因此我知道它们正在发送回给我;然而,在代码中访问它们似乎对我不起作用。这是代码(其基本的获取承诺链接):

fetch(url)
  .then(response => {
    for (let header of response.headers) { < -- - headers is empty
      console.log(header);
    }
    return response;
  });
Run Code Online (Sandbox Code Playgroud)

但response.headers是空的。但我可以清楚地看到 Chrome 中的标题。提取调用阻止我查看它们是否有原因?我需要什么才能访问这些标头?服务器存储了一些我们想要使用的特定于应用程序的标头。

更新:我可以通过让服务器将其添加到 OPTION 请求的响应中来解决此问题:

response.setHeader("Access-Control-Expose-Headers", "X-Custom-Header");
Run Code Online (Sandbox Code Playgroud)

现在,根据 fetch 命令的响应,我可以执行以下操作:

const customHeader = response.headers.get('X-Custom-Header');
Run Code Online (Sandbox Code Playgroud)

谢谢卡里姆对此的帮助!

Kar*_*rim 5

要获取特定标头,您需要调用response.headers.get(key)

可迭代对象是response.headers.entries而不是response.headers

for (let header of response.headers.entries()) {
  console.log(header);
}
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries

此外,在 cors 场景中,只有一些标头会暴露给应用程序,因此您在 chrome 开发工具上看到的所有标头不一定在应用程序级别可用。有关更多详细信息,请查看此答案:

使用 Fetch API 读取响应标头

  • 卡里姆,谢谢你。通过让服务器将其添加到 OPTIONS 请求的响应标头中,我能够弄清楚这一点:response.setHeader("Access-Control-Expose-Headers", "X-Auth-Access"); (3认同)
  • 请记住,在 cors 场景中仅公开一些标头:/sf/ask/3034137361/?utm_medium=organic&amp;utm_source=google_rich_qa&amp;utm_campaign=google_rich_qa (2认同)