【发布时间】:2020-10-02 19:41:11
【问题描述】:
我现在已经花费了无数个小时来尝试让缓存 API 来缓存一个简单的请求。我让它在两者之间工作过一次,但忘记在缓存键中添加一些东西,现在它不再工作了。不用说,cache.put() 没有返回值来指定请求是否实际被缓存并没有帮助,我只能反复试验。有人可以告诉我我做错了什么以及实际需要什么吗?我现在已经阅读了所有文档超过 3 遍,我很茫然……
值得注意的是,这个 REST 端点设置了pragma: no-cache 和所有其他与无缓存相关的缓存,但我想强制缓存响应,这就是为什么我试图在缓存之前完全重写标题,但是它仍然无法正常工作(不匹配或不存储,没人知道......)
async function apiTest(token, url) {
let apiCache = await caches.open("apiResponses");
let request = new Request(
new URL("https://api.mysite.com/api/"+url),
{
headers: {
"Authorization": "Bearer "+token,
}
}
)
// Check if the response is already in the cloudflare cache
let response = await apiCache.match(request);
if (response) {
console.log("Serving from cache");
}
if (!response) {
// if not, ask the origin if the permission is granted
response = await fetch(request);
// cache response in cloudflare cache
response = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: {
"Cache-Control": "max-age=900",
"Content-Type": response.headers.get("Content-Type"),
}
});
await apiCache.put(request, response.clone());
}
return response;
}
在此先感谢您的帮助,我首先在 Cloudflare 社区提出了同样的问题,但 2 周内没有收到答复
【问题讨论】:
标签: javascript service-worker cloudflare cloudflare-workers cacheapi