我想从使用策略令牌作为URL参数的安全CDN缓存资产。例如:www.cdn.com/image.png?Policy=AAAAA&Key-Pair-Id=BBBBB
,如果我重新访问该网站,即使我有不同的策略令牌和密钥对ID,我也想从缓存中获取资产。例如:www.cdn.com/image.png?Policy=CCCCC&Key-Pair-Id=DDDDD
如果我在服务工作者中使用此代码:
workbox.routing.registerRoute(
/^(http(s)?:)?\/\/www\.cdn\.com.*/,
workbox.strategies.staleWhileRevalidate()
);
它在缓存中找不到响应并进入网络。我希望它匹配不带URL参数的URL(即使Policy = CCCCC&Key-Pair-Id = DDDDD实际上不是有效的策略)。看看www.cdn.com/image.png
是否存在并检索它。
我通过使用自定义处理程序找到了解决方案:
workbox.routing.registerRoute(
/^(http(s)?:)?\/\/www\.cdn\.com.*/,
({url, event}) => {
return caches.open(`${prefix}-${runtime}-${suffix}`).then((cache) => {
const customRequest = `${url.origin}${url.pathname}`;
return cache.match(customRequest).then((cacheRes) => {
if (cacheRes) {
return cacheRes;
}
return fetch(event.request).then((fetchRes) => {
cache.put(customRequest, fetchRes.clone());
return fetchRes;
});
});
});
}
);