【问题标题】:Read headers from CORS response return empty object [closed]从 CORS 响应读取标头返回空对象 [关闭]
【发布时间】:2021-07-27 13:29:21
【问题描述】:

当我在浏览器中使用 javascript 进行提取(使用基本身份验证)时,我会收到屏幕截图中的响应。 这很好,但是为什么console.log(response.headers) 返回一个空对象呢?

我添加了 acces-control-expose-headers,因为这是一个 cors 请求,我想知道日期。

目标是缓存响应(缓存 API)并使用日期来获取缓存的年龄。 但缓存版本也不返回标头。 (但使用 chrome 中的开发工具,我可以看到所有标题都在缓存中)

下面是部分代码:

    const cache = await caches.open('data');
    let response = await cache.match(url)
    if (!response) {
      response = await fetch(url, {
        headers: new Headers({
          "Authorization": 'Basic 1234fake567=='
        })
      });
      if (!response.ok) return dispatch(setError(response.status.toString()));
      console.log(response.headers)  // => {}
      await cache.put(url, response)
      response = await cache.match(url)
    }
    console.log(response.headers) // => {}
    const apiData: ApiData = await response.json();

【问题讨论】:

  • 你的脚本是什么?可以发一点吗?
  • 试试response.headers.forEach((value, key) => console.log(key, value)); 您也可以使用response.headers.get('...')获取单独的标头
  • 您是否正在等待您的 fetch 正确?需要看代码。
  • 我添加了一些代码
  • 可能是因为SO post中提到的CORS限制?

标签: javascript cors http-headers


【解决方案1】:

根据这个SO post,您不能使用console.log(response.headers) 来调试打印标题。试试这个:

    const cache = await caches.open('data');
    let response = await cache.match(url)
    if (!response) {
      response = await fetch(url, {
        headers: new Headers({
          "Authorization": 'Basic 1234fake567=='
        })
      });
      if (!response.ok) return dispatch(setError(response.status.toString()));
      

      // This is new
      for (var pair of response.headers.entries()) {
         console.log(pair[0]+ ': '+ pair[1]);
      }

      await cache.put(url, response)
      response = await cache.match(url)
    }
    console.log(response.headers) // => {}
    const apiData: ApiData = await response.json();

【讨论】:

  • 该死,这行得通:response.headers.get('Date')。我确实尝试过,但是在添加该 cors 标头之前我已经知道并且没有再试一次。谢谢!
  • 刚刚意识到,这就是 Chris G 在 cmets 中提到的
  • 是的,我不敢相信这会起作用 :-) 我读了那个 SO 帖子,但第一个答案只是解决方案的一部分。第二个答案现在是我的解决方案。
  • @roeland 老实说,这很模糊,result.headers 打印为 {} 给人一种错误的印象,它有效
  • 如果您发现现有问题,请不要发布答案。将其标记为重复。
猜你喜欢
  • 2016-09-02
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2013-03-10
  • 1970-01-01
  • 2020-01-25
相关资源
最近更新 更多