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

Next.js App Router中getImage未请求后端却返回缓存数据的问题

问题分析与解决方案

问题原因

在Next.js App Router中,fetch API默认会对请求结果进行缓存——哪怕是POST请求,开发或生产环境下都会触发这个机制。你的Home页面是异步组件(默认SSR),首次请求后数据被缓存,后续服务器端不会再发起新的后端请求,而是直接返回缓存数据,这就是你看不到网络请求记录的核心原因。

解决方案

针对每日天文图片的场景,提供两种适配处理方式:

1. 强制禁用缓存(每次请求都获取最新数据)

修改getImage函数中的fetch配置,添加cache: 'no-store'选项,强制跳过缓存:

const url = process.env.NEXT_PUBLIC_BACKEND_URL;

export default async function getImage() {
  try {
    const res = await fetch(`${url}/nasaImage`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      cache: 'no-store', // 关键:禁用缓存,每次请求都调用后端
    });

    if (!res.ok) {
      throw new Error(`Error loading image: ${res.statusText}`);
    }

    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err.message);
    throw new Error("Error loading Astronomical Picture of the Day");
  }
}

2. 设置定时重新验证(适配每日更新场景)

如果天文图片固定每日更新,可以设置next.revalidate选项,让缓存数据在指定时间后自动刷新(比如24小时):

const url = process.env.NEXT_PUBLIC_BACKEND_URL;

export default async function getImage() {
  try {
    const res = await fetch(`${url}/nasaImage`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      next: { revalidate: 86400 }, // 24小时(86400秒)后重新获取数据
    });

    if (!res.ok) {
      throw new Error(`Error loading image: ${res.statusText}`);
    }

    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err.message);
    throw new Error("Error loading Astronomical Picture of the Day");
  }
}

补充说明

  • 服务器端的fetch请求不会出现在浏览器网络面板中,因为数据是在服务器端获取后直接渲染到HTML里返回给客户端的,只有客户端组件发起的请求才会在浏览器面板显示。
  • 若开发环境仍有缓存残留问题,可以重启开发服务器,或使用next dev --no-cache命令启动,临时禁用开发环境缓存。

内容的提问来源于stack exchange,提问作者Namandeep Singh Wadhwa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:38:14