Che*_*yne 2 javascript cloudflare cloudflare-workers
我刚刚在这个简单的工人身上花了一整天的时间,但我一无所获。
我已经关注了 CloudFlare 网站上的 Cache API 示例,也浏览了 StackOverflow 的帖子,但仍然一无所获。
这篇文章(Cloudflares Worker Cache API 的问题)看起来正是我所需要的,但它没有帮助。
本质上,我想做的就是使用缓存 API 将某些页面缓存一段时间。我最终需要根据国家/地区代码执行特定的缓存(这就是为什么我使用工作程序而不是页面规则),但现在我要做的就是让基本缓存 API 作为测试工作。
这是代码,它与他们网站上的示例代码基本相同
处理程序.ts
export async function handleRequest(event: FetchEvent): Promise<Response> {
const { request } = event
const cacheUrl = new URL(request.url)
const cacheKey = new Request(cacheUrl.toString(), request)
const cache = caches.default
let response = await cache.match(cacheKey)
if (!response) {
console.log('NO CACHE MATCH')
// If not in cache, get it from origin
response = await fetch(request)
// Must use Response constructor to inherit all of response's fields
response = new Response(response.body, response)
response.headers.append('Cache-Control', 's-maxage=10')
event.waitUntil(cache.put(cacheKey, response.clone()))
}
return response
}
Run Code Online (Sandbox Code Playgroud)
索引.ts
import { handleRequest } from './handler'
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event))
})
Run Code Online (Sandbox Code Playgroud)
我知道您无法在workers.dev域中使用Cache API,因此我已将worker部署到自定义域,因此它应该可以访问该API。
我努力了
基本上,我只是得到缓存未命中,请求就会发送到我的网络服务器。我可以看到控制台日志,一切都运行良好,它只是从不缓存或从未找到缓存。
调试起来非常困难,而且这些方法几乎没有返回任何信息。cache.put 不返回任何内容,cache.match 不返回任何内容。他们也可能会被嘲笑。
我使用牧马人来构建/发布,一切都工作正常。
有人可以帮忙吗?
小智 6
我认为你的代码看起来非常简单/有意义。所以,对我来说,下一个可能性似乎是某种数据问题(例如响应格式)。某些标头(例如Cache-Control特定Set-Cookie标头)会影响是否可以缓存 - https://developers.cloudflare.com/workers/runtime-apis/cache#headers
您能否验证您的响应不包含使其无法缓存的内容?如果您能够共享完整的响应或仅共享标题,那也会有所帮助。
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |