使用正则表达式路由使工作箱缓存跨源请求

问题描述 投票:0回答:2

我想使用工作盒服务工作程序将所有json资源缓存在我网站的CDN上的目录中

资源网址:

https://cdn.example.com/mydir/*.json

我的服务人员在:

https://example.com/service-worker.js

我写了我的缓存代码如下

workbox.routing.registerRoute(
    /mydir\/.+\.json$/,
    new workbox.strategies.CacheFirst({
        plugins: [
            new workbox.cacheableResponse.Plugin({
                statuses: [0, 200]
            })
        ]
    })
);

但是我从工作箱中收到此错误:

The regular expression '/mydir\/.+\.json$/' only partially matched against the cross-origin URL 'https://cdn.example.com/mydir/test.json'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.

我如何在我的服务工作者中缓存这些资源?有什么主意吗?

cross-domain workbox
2个回答
1
投票

您必须调整您的正则表达式,使其与整个域匹配。稍微冗长一些,但可以确保您确实要缓存该缓存,并且要缓存来自确切域的缓存。

因此路径(/mydir/bla/blu/bla.json)不够,请与整个地址(https://sub.domain.com/mydir/bla/blu/bla.json)匹配。


0
投票

我在worbox路由文档中找到了我的答案:

但是,对于跨域请求,正则表达式必须与URL的开头。原因是不太可能使用您想要的正则表达式new RegExp('/styles/.*\\.css')匹配第三方CSS文件。

https://cdn.third-party-site.com/styles/main.css
https://cdn.third-party-site.com/styles/nested/file.css
https://cdn.third-party-site.com/nested/styles/directory.css

如果确实想要这种行为,您只需要确保常规表达式匹配URL的开头。如果我们想匹配对于https://cdn.third-party-site.com的请求,我们可以使用常规表达new RegExp('https://cdn\\.third-party-site\\.com.*/styles/.*\\.css')

https://cdn.third-party-site.com/styles/main.css
https://cdn.third-party-site.com/styles/nested/file.css
https://cdn.third-party-site.com/nested/styles/directory.css

所以我将路由正则表达式更改为:

/^https:\/\/cdn\.example\.com\/mydir\/.+\.json$/

现在工作箱缓存正在工作

© www.soinside.com 2019 - 2024. All rights reserved.