我正在使用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]}
})
);
知道如何在响应中添加标题吗?
谢谢!
答案 0 :(得分:2)
它有点埋没在文档中,但您可以使用实现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;
}
);