You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cloudflare Worker中实现fetch请求至少24小时的长期缓存

问题原因及修复方案

你的Worker缓存未生效是核心配置缺失导致的,修改后的可用代码如下:

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
});

async function handleRequest(request) {
  const url = 'https://www.unixtimestamp.com/'
  let response = await fetch(url, {
    cache: "force-cache", // 显式开启跨域请求缓存
    cf: {
      ignoreOriginCacheControl: true, // 忽略源站的缓存控制头,优先用自定义TTL
      cacheTtlByStatus: { "200-299": 86400, 404: -1, "500-599": -1 }
    }
  })
  return response
}

必须修改的配置说明

  • cache: "force-cache":Cloudflare Worker默认不会对跨域的第三方请求走边缘缓存,必须添加这个参数显式启用缓存逻辑
  • cf.ignoreOriginCacheControl: true:源站unixtimestamp.com返回的响应头包含Cache-Control: no-store等禁止缓存的配置,不加这个参数的话自定义的TTL会被源站配置覆盖,缓存无法生效

更可靠的Cache API版本(可选)

如果需要完全自主控制缓存逻辑,避免fetch隐式缓存的兼容问题,可以直接调用Cloudflare内置的Cache API实现:

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
});

async function handleRequest(request) {
  // 自定义缓存键,这里用目标地址作为缓存键
  const cacheKey = new Request("https://www.unixtimestamp.com/", { method: "GET" })
  const cache = caches.default

  // 先查缓存是否存在
  let response = await cache.match(cacheKey)
  if (response) {
    return response
  }

  // 缓存不存在则请求源站
  response = await fetch("https://www.unixtimestamp.com/")

  // 将响应写入缓存,注意要克隆响应,因为响应流只能读取一次
  event.waitUntil(cache.put(cacheKey, response.clone()))
  // 手动设置缓存过期头,确保24小时过期
  response = new Response(response.body, {
    ...response,
    headers: {
      ...response.headers,
      "Cache-Control": "s-maxage=86400"
    }
  })
  return response
}

内容的提问来源于stack exchange,提问作者sparkle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:12:03