Workbox - 添加 header 到缓存响应

Workbox - add header to cached response

我正在使用 workbox-sw 来缓存一些 API 请求,我想知道是否可以将自定义 header 添加到从缓存返回的响应中。

我的 sw.js 看起来像这样:

importScripts('workbox-sw.prod.v2.1.1.js');

const workboxSW = new WorkboxSW();

workboxSW.precache([]);
workboxSW.router.registerRoute(
  new RegExp('^https://api\.url/'),
  workboxSW.strategies.cacheFirst({
    cacheName: 'api-cache',
    cacheExpiration: {
      maxEntries: 10,
      maxAgeSeconds: 3600 * 24
    },
    cacheableResponse: {statuses: [200]}
  })
);

知道如何在响应中添加 header 吗?

谢谢!

它有点隐藏在文档中,但您可以使用实现 handlerCallback interface 的函数在 Route 匹配时执行自定义操作,如下所示:

const cacheFirstStrategy = workboxSW.strategies.cacheFirst({
  cacheName: 'api-cache',
  cacheExpiration: {
    maxEntries: 10,
    maxAgeSeconds: 3600 * 24
  },
  cacheableResponse: {statuses: [200]}
});

workboxSW.router.registerRoute(
  new RegExp('^https://api\.url/'),
  async ({event, url}) => {
    const cachedResponse = await cacheFirstStrategy.handle({event, url});
    if (cachedResponse) {
      cachedResponse.headers.set('x-custom-header', 'my-value');
    }
    return cachedResponse;
  }
);