从 CORS 响应 return 中读取 headers 为空 object

Read headers from CORS response return empty object

当我在浏览器中使用 javascript 进行抓取时(使用基本身份验证),我得到了类似于屏幕截图中的响应。 这很好,但是为什么 console.log(response.headers) return 是空的 object?

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

目标是缓存响应(Cache API)并使用日期获取缓存的年龄。 但缓存版本也没有 return headers。 (但是使用 chrome 中的开发工具,我可以看到所有 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()));
      console.log(response.headers)  // => {}
      await cache.put(url, response)
      response = await cache.match(url)
    }
    console.log(response.headers) // => {}
    const apiData: ApiData = await response.json();

根据此 SO post,您不能使用 console.log(response.headers) 调试打印 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();