【问题标题】:ES6: Retrieve response headers from a CORS fetch callES6:从 CORS 获取调用中检索响应标头
【发布时间】:2019-09-08 22:54:33
【问题描述】:

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

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

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

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

response.setHeader("Access-Control-Expose-Headers", "X-Custom-Header");

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

const customHeader = response.headers.get('X-Custom-Header');

感谢卡里姆对此提供的帮助!

【问题讨论】:

    标签: javascript ecmascript-6 cors fetch


    【解决方案1】:

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

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

    for (let header of response.headers.entries()) {
      console.log(header);
    }
    

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

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

    Reading response headers with Fetch API

    【讨论】:

    • 我试过没有用。 response.headers.entries() 返回一个空的迭代器。即使我在 Chrome DevTools 中查看 response.headers.get('my-custom-header') ,它也会返回 undefined 。很奇怪。
    • 请记住,在 cors 方案中只公开了一些标头:stackoverflow.com/questions/43344819/…
    • 卡里姆,谢谢。通过让服务器将其添加到 OPTIONS 请求的响应标头中,我能够弄清楚这一点: response.setHeader("Access-Control-Expose-Headers", "X-Auth-Access");
    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 2013-08-27
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多