如何使工作箱缓存跨源响应? [英] How to make workbox cache cross origin responses?
问题描述
根据workbox doc,跨域请求应该是配置以确保正则表达式匹配 URL 的开头.但是,它不起作用.
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.
Service Worker 代码如下.
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()
);
在页面中,来自同源资源的响应被缓存,但来自https://a248.e.akami.net
的响应没有.
In the page, responses from same origin resources are cached, but responses from https://a248.e.akami.net
is not.
我的配置有问题吗?还是这是一个工作箱 3.0.0 的错误?
Anything wrong with my config? or is this a workbox 3.0.0 bug?
推荐答案
您的 https://a248.e.akami.net
服务器上是否启用了 CORS?如果没有,您将收到不透明的回复,默认情况下,当使用 cacheFirst
策略时,这些不会被缓存.
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.
有一个指南,用于处理第三方如果您想在使用 cacheFirst
策略时选择缓存这些响应,可以使用带有配方的请求:
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]
})
]
}),
);
当出现这种情况时,在 localhost 中使用 Workbox v3 时,您还应该看到 JavaScript 控制台中记录的新警告,说明发生了什么.
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.
这篇关于如何使工作箱缓存跨源响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!