2 回答
TA贡献1982条经验 获得超2个赞
我建议你写一个使用的自定义插件cacheWillUpdate的回调,并采取适当的行动,如果传入的状态Response是401。(在后台workbox-cacheable-response使用cacheWillUpdate,但是您需要更多的灵活性,因此编写自己的逻辑是有意义的。)
就像是:
// Or use workbox.core.cacheNames.runtime for the default cache.
const cacheName = 'my-api-cache';
const myPlugin = {
cacheWillUpdate: async ({response}) => {
if (response.status === 401) {
const cache = await caches.open(cacheName);
await cache.delete(response.url);
return null;
}
// Add in any other checks here, if needed.
return response;
},
};
workbox.routing.registerRoute(
/^\/api\/data.json$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName,
plugins: [myPlugin],
})
);
TA贡献2065条经验 获得超14个赞
因此,这是我的解决方法:
我使用workbox.cacheableResponse.Plugin来缓存401响应。然后,我添加了另一个插件,该插件检查缓存的响应是否成功。如果没有(即401收到),我将不返回任何缓存结果:
workbox.routing.registerRoute(
/^\/api\/data.json$/,
new workbox.strategies.StaleWhileRevalidate({
plugins: [
// explicitly allow to cache `401` …
new workbox.cacheableResponse.Plugin({ statuses: [0, 200, 401] }),
// … but do not return a cached result
// in this case (!cachedResponse.ok)
{
cachedResponseWillBeUsed: ({ cachedResponse }) => {
return (cachedResponse && cachedResponse.ok) ? cachedResponse : null;
}
}
]
})
);
添加回答
举报