问题
According to workbox doc, cross domain request should be configured to ensure that regular expression matches the beginning of the URL. However, it doesn't work.
The service worker code is like below.
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js');
workbox.routing.registerRoute(
/.*\.(png|jpg|jpeg|svg|gif)/,
workbox.strategies.cacheFirst()
);
workbox.routing.registerRoute(
new RegExp('^https://a248.e.akamai.net/.*'),
workbox.strategies.cacheFirst()
);
In the page, responses from same origin resources are cached, but responses from https://a248.e.akami.net
is not.
Anything wrong with my config? or is this a workbox 3.0.0 bug?
回答1:
Do you have CORS enabled on your https://a248.e.akami.net
server? If not, you'll be getting back opaque responses, and by default, those will not be cached when using a cacheFirst
strategy.
There's a guide for handling third-party requests with a recipe you could use if you want to opt-in to caching those responses when using a cacheFirst
strategy:
workbox.routing.registerRoute(
new RegExp('^https://a248.e.akamai.net/.*'),
workbox.strategies.cacheFirst({
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200]
})
]
}),
);
You should also see a new warning logged in the JavaScript console when using Workbox v3 in localhost when this situation arises, explaining what's going on.
来源:https://stackoverflow.com/questions/49295757/how-to-make-workbox-cache-cross-origin-responses