微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 是否可以修改服务工作者缓存响应头?

我正在尝试标记存储在服务工作缓存中的资源.

我认为可以向资源添加一个可以指示此情况的自定义标头,但是,一旦资源存储在服务工作缓存中,就会删除标头修改.是这样的吗?我在cache spec中没有看到有关修改响应头的任何内容.

这是我尝试过的一个例子:

// I successfully cache a resource (confirmed in Dev Tools)
caches.open('testCache').then(cache => {
    cache.add('kitten.jpg');
})
.then(() => {
    console.log('successfully cached image'); // logs as expected
});

// placeholder
var modifiedResponse;

// get the cached resource
caches.open('testCache')
.then(cache => {
  return cache.match('kitten.jpg');
})

// modify the resource's headers
.then(response => {
  modifiedResponse = response;
  modifiedResponse.headers.append('x-new-header','test-value');
  // confirm that the header was modified
  console.log(modifiedResponse.headers.get('x-new-header')); // logs 'test-value'
  return caches.open('testCache');
})

// put the modified resource back into the cache
.then((cache) => {
  return cache.put('kitten.jpg',modifiedResponse);
})

// get the modified resource back out again
.then(() => {
  return caches.match('kitten.jpg');
})

// the modifed header wasn't saved!
.then(response => {
  console.log(response.headers.get('x-new-header')); // logs null
});

我还尝试删除自定义标头,修改现有标头,并创建一个新的Response()响应对象,而不是抓取现有的.

编辑:我正在使用Chrome 56.

解决方法

您必须创建一个新的响应来执行此操作:
fetch('./').then(response => {
  console.log(new Map(response.headers));

  const newHeaders = new Headers(response.headers);
  newHeaders.append('x-foo','bar');

  const anotherResponse = new Response(response.body,{
    status: response.status,statusText: response.statusText,headers: newHeaders
  });

  console.log(new Map(anotherResponse.headers));
});

Live demo(见控制台)

原文地址:https://www.jb51.cc/js/157590.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐