【问题标题】:Workbox - add header to cached response工作箱 - 将标头添加到缓存的响应
【发布时间】:2019-05-09 10:36:47
【问题描述】:

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

我的 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]}
  })
);

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

谢谢!

【问题讨论】:

    标签: javascript caching workbox


    【解决方案1】:

    它有点隐藏在文档中,但您可以使用实现 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;
      }
    );
    

    【讨论】:

    • chrome 抱怨 - Uncaught (in promise) TypeError: Failed to execute 'set' on 'Headers': Headers are immutable
    • @denov 看看另一个 Jeff 的回答:stackoverflow.com/a/30063346/2234964 这是避免此错误的可能方法。
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多