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

React+Axios API响应缓存问题:仅禁用DevTools缓存才更新

解决axios请求被浏览器缓存的问题

针对你遇到的axios请求返回缓存数据、无法获取最新结果的问题,以下是几个实用的生产环境可用解决方案:

方案一:添加禁用缓存的请求头

在axios请求拦截器中设置强制不缓存的HTTP头,直接告诉浏览器跳过缓存、每次从服务器拉取最新数据。修改你的请求拦截器代码,新增以下headers配置:

instance.interceptors.request.use(
  async function (config) {
    let authority = getAuthority();
    var headers = { ...config.headers };
    
    // 新增禁用缓存的请求头
    headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
    headers['Pragma'] = 'no-cache';
    headers['Expires'] = '0';
    
    if (authority) {
      headers['Authorization'] = `Bearer ${authority}`;
    }
    headers['X-Requested-With'] = 'XMLHttpRequest';
    headers['Content-Type'] = 'application/json';
    headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
    config.headers = headers;
    return config;
  },
  // ... 原错误处理代码
);

方案二:给GET请求添加唯一参数

浏览器对GET请求的缓存敏感度更高,通过在URL末尾添加随时间变化的参数(比如时间戳),让每个请求的URL都独一无二,从而绕过缓存。在请求拦截器中加入以下逻辑:

instance.interceptors.request.use(
  async function (config) {
    // 仅对GET请求添加随机时间戳参数
    if (config.method?.toLowerCase() === 'get') {
      const timestamp = Date.now();
      config.url += config.url.includes('?') ? `&_t=${timestamp}` : `?_t=${timestamp}`;
    }
    
    let authority = getAuthority();
    var headers = { ...config.headers };
    // ... 原headers设置代码
    config.headers = headers;
    return config;
  },
  // ... 原错误处理代码
);

方案三:协调后端修改响应头

如果前端配置后仍存在缓存问题,可能是后端返回的响应头包含了缓存指令(比如Cache-Control: max-age=3600)。需要后端在接口响应中设置:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

确保服务器明确告知浏览器不要缓存该接口的响应。

可以根据实际场景选择一种或多种方案组合使用,前两种前端方案足以解决绝大多数生产环境的缓存问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:40:57