【问题标题】:Cache Storage API, can't get header back缓存存储 API,无法取回标头
【发布时间】:2019-04-26 19:50:47
【问题描述】:

我想检查 max-age 以便在项目变旧时从缓存中删除它们,但由于某种原因我无法取回自己的标头。

  export function cacheResponse(url, response) {
          caches.open('my-cache').then(function(cache) {
            cache.put(url, new Response(JSON.stringify(response), {
              headers: {
                'Cache-Control': 'max-age=1',
                'Content-Type': 'application/json;charset=UTF-8'
              }
            }));
          });
        }

cacheResponse('/hello', {hello: "world"})

我可以在 chrome 的 Application 选项卡中看到这个工作,我可以在预览中看到这 2 个标题,但是当我将项目拉回时,headers 对象为空。

cache.match(url).then(async function(object) {
  console.log(object.headers) // null
  var body = await object.clone().json(); // {hello: "world"}
})

对象看起来像这样

object: Response
body: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: ""
type: "default"
url: ""

似乎我应该能够通过调用 match() 来查找标题?

【问题讨论】:

    标签: javascript google-chrome service-worker browser-cache


    【解决方案1】:

    应该可以的;您应该可以调用response.headers.get('cache-control') 来检索值(假设这是同源响应)。

    这是我刚刚测试过的在 JS 控制台中运行的代码的 sn-p:

    async function test() {
      const constructedResponse = new Response('test', {
        headers: {'cache-control': 'max-age=1'}
      });
    
      const cache = await caches.open('test');
    
      cache.put('/test', constructedResponse);
    
      const matchedResponse = await cache.match('/test');
    
      console.log(`cache-control: ${matchedResponse.headers.get('cache-control')}`);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2019-03-26
      • 2017-02-12
      相关资源
      最近更新 更多