简体   繁体   English

缓存存储API,无法获取头

[英]Cache Storage API, can't get header back

I would like to a check for max-age so I remove items from cache when they get old, but I can't get my own header back for some reason. 我想检查一下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"})

I can see this working in the Application tab in chrome and I can see those 2 headers in the preview, but when I pull the item back out the headers object is null. 我可以看到这在chrome中的Application选项卡中工作,我可以在预览中看到这两个标题,但是当我将项目拉出时, headers对象为null。

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

The object looks like this 该对象看起来像这样

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

Seems like I should be able to lookup the headers from calling match() no? 好像我应该能够通过调用match()来查找标题吗?

That should work; 那应该有用; you should be able to call response.headers.get('cache-control') to retrieve the value (assuming this is a same-origin response). 你应该能够调用response.headers.get('cache-control')来检索值(假设这是一个同源响应)。

Here's a snippet of code that I just tested which worked when run in the JS console: 这是我刚刚测试过的一段代码,它们在JS控制台中运行时有效:

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')}`);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM