繁体   English   中英

CloudFlare Worker Cache API 不存储提取结果

[英]CloudFlare Worker Cache API Not Storing Fetch Results

我刚刚在这个简单的工人身上花了一整天,但我无处可去。

我在 CloudFlare 站点上关注了缓存 API 示例,也浏览了 StackOverflow 的帖子,但我仍然无处可去。

这篇文章( Cloudflares Worker Cache API 有问题)看起来正是我所需要的,但它没有帮助。

基本上,我试图做的就是使用缓存 API 将某些页面缓存一段时间。 我最终需要为每个国家/地区代码做特定的缓存(这就是为什么我使用工作程序而不是页面规则)但现在我试图做的就是让基本的缓存 API 作为测试工作。

这是代码,它基本上与他们网站上的示例代码相同

处理程序

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
}

索引.ts

import { handleRequest } from './handler'

addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event))
})

我知道您不能在 workers.dev 域中使用 Cache API,所以我已将 worker 部署到自定义域,因此它应该可以访问 API。

我试过了

  • 从 cache.put 中注销响应 - 什么都没有
  • 将缓存键从 Response obj 更改为 URL(字符串) - 没有
  • 直接等待 cache.put - 什么都没有
  • 使用自定义缓存命名空间(所以 await caches.open('pages')) - 没有

基本上,我只是缓存未命中,请求会传递到我的网络服务器。 我可以看到控制台日志,一切都运行良好,只是从不缓存或从未找到缓存。

调试起来非常困难,而且这些方法几乎没有返回任何信息。 cache.put 不返回任何内容, cache.match 不返回任何内容。 他们也可能被嘲笑。

我使用 wrangler 来构建/发布,并且一切正常。

有人可以在这里提供帮助吗?

我认为你的代码看起来很简单/有意义。 所以,对我来说,下一个可能性似乎是某种数据问题(例如,响应格式)。 某些标头,例如Cache-Control和特别是Set-Cookie会影响它是否可以缓存 - https://developers.cloudflare.com/workers/runtime-apis/cache#headers

您能否验证您的响应不包含使其无法缓存的内容? 如果您能够分享完整的回复,或仅分享标题,那也会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM