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

调用fetch时如何设置缓存条目的最大有效期?

如何用Fetch指定仅使用不超过X分钟的缓存版本

你对fetch缓存逻辑的理解有部分偏差,咱们拆解清楚:

首先,你设置的请求头Cache-Control: max-age=180确实只作用于服务器通信——它告诉服务器“我只接受缓存时长不超过180秒的资源”,但浏览器本地是否使用缓存,核心是由服务器返回的响应头Cache-Control决定的。比如如果服务器响应头写了max-age=3600,那浏览器会在1小时内直接用本地缓存,完全忽略你请求头里的max-age设置。

要实现“仅使用不超过X分钟的缓存”,分两种场景处理:

场景一:能控制服务器响应头

这是最标准的解决方案,直接让服务器在返回资源时添加响应头:

Cache-Control: max-age=180

这样浏览器会自动在3分钟内直接读取本地缓存,超过时长才会向服务器请求新内容。

场景二:无法控制服务器响应头

这种情况需要手动管理缓存,比如借助浏览器的Cache API或localStorage存储资源和对应的时间戳,自己判断缓存是否过期:

示例代码(基于Cache API):

async function fetchWithMaxAge(url, maxAgeSeconds) {
  const cache = await caches.open('custom-resource-cache');
  const cachedResponse = await cache.match(url);

  if (cachedResponse) {
    // 取出缓存时记录的时间戳
    const cachedTime = new Date(cachedResponse.headers.get('X-Cache-Timestamp'));
    const now = new Date();
    // 校验缓存是否在有效期内
    if (now - cachedTime <= maxAgeSeconds * 1000) {
      return cachedResponse.clone();
    }
    // 缓存过期,删除旧缓存
    await cache.delete(url);
  }

  // 发起新请求并缓存结果
  const response = await fetch(url);
  if (response.ok) {
    const responseToCache = response.clone();
    const headers = new Headers(responseToCache.headers);
    // 添加自定义时间戳头,方便后续校验
    headers.set('X-Cache-Timestamp', new Date().toISOString());
    await cache.put(url, new Response(responseToCache.body, {
      status: responseToCache.status,
      statusText: responseToCache.statusText,
      headers: headers
    }));
  }
  return response;
}

// 使用示例:获取不超过3分钟(180秒)的缓存资源
const r = await fetchWithMaxAge('someurl', 180);

补充说明

你之前用的cache: "reload"会强制跳过本地缓存,直接从服务器拉取,等价于设置请求头Cache-Control: no-cache, no-store, must-revalidate。而cache: "no-cache"是让浏览器先向服务器验证缓存有效性(发送If-Modified-Since或If-None-Match头),服务器返回304则用本地缓存,否则返回新内容,但这种方式无法直接指定缓存时长,还是得依赖服务器响应头或手动缓存管理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:12:45