[英]Serve different cache versions using the same URL through cloudflare worker
我从许多使用不同版本的移动和桌面网站的人那里看到了一个非常常见的问题,许多主题都具有此功能。 问题是无论用户设备如何,Cloudflare 都会缓存相同的页面,从而导致桌面和移动版本之间的混合和不一致。
最常见的解决方案是将移动版本分成另一个 URL,但在我的情况下,我想使用相同的 URL 并使 Cloudflare 缓存在桌面和移动设备上都能正常工作。
我发现这个非常好的指南展示了如何解决这个问题,但是,工作代码似乎已经过时,我不得不修改一些部分以使其工作。
我为我的工作人员创建了一个新的子域,然后将路由分配到我的站点,以便它开始运行。
工作人员正在缓存所有内容,但是,它没有根据设备具有不同缓存版本的所需功能。
async function run(event) {
const { request } = event;
const cache = caches.default;
// Read the user agent of the request
const ua = request.headers.get('user-agent');
let uaValue;
if (ua.match(/mobile/i)) {
uaValue = 'mobile';
} else {
uaValue = 'desktop';
}
console.log(uaValue);
// Construct a new response object which distinguishes the cache key by device
// type.
const url = new URL(request.url);
url.searchParams.set('ua', uaValue);
const newRequest = new Request(url, request);
let response = await cache.match(newRequest);
if (!response) {
// Use the original request object when fetching the response from the
// server to avoid passing on the query parameters to our backend.
response = await fetch(request, { cf: { cacheTtl: 14400 } });
// Store the cached response with our extended query parameters.
event.waitUntil(cache.put(newRequest, response.clone()));
}
return response;
}
addEventListener('fetch', (event) => {
event.respondWith(run(event));
});
它确实在检测正确的用户代理,但根据分配的查询字符串,它应该有两个单独的缓存版本......
我想也许我缺少一些配置,我不知道为什么它没有按预期工作。 就像现在一样,我仍然混合使用我的移动和桌面缓存版本。
这里的问题是fetch()
本身已经进行了正常的缓存,与您使用它周围的缓存 API 无关。 因此fetch()
可能仍会返回针对错误 UA 的缓存响应。
如果您可以让后端忽略查询参数,那么您可以将查询包含在传递给fetch()
的请求中,以便它以不同的方式正确缓存两个结果。 (企业客户可以使用自定义缓存键来完成此操作,而无需更改 URL。)
如果你这样做,那么你也可以删除cache.match()
和 cache.put( cache.put()
调用,因为fetch()
本身将处理缓存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.