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

Next.js Fetch请求异常求助:已删数据库仍返回旧数据

问题:Next.js Fetch请求返回旧数据,Postman请求正常

问题详情

  • 已删除目标API对应的数据库,理论上接口不应返回旧数据
  • 前端Next.js应用运行在localhost:3000/images,调用接口http://localhost:4000/api/getImages时,控制台仍显示旧数据
  • 使用Postman访问同一接口,能正常获取(空)数据

相关代码:

async function loadImg(){
  const res = await fetch("http://localhost:4000/api/getImages")
  const data = await res.json()
  return data
}


export default async function ImgPage() {
  const imgs = await loadImg()
  console.log(imgs)

  return (
    <div>
      {imgs.map((img)=>(
        <div key={img._id}>

          <h3>{img.date}</h3>
          <img src={"http://localhost:4000/files/"+img.filename} alt={img.originalname}></img>
        </div>
      ))}
    </div>
  )
}

原因分析

Next.js存在内部缓存机制,尤其是在服务器组件(你的ImgPage是async服务器组件)场景下,fetch请求默认会启用缓存(等同于cache: 'force-cache'),这会导致请求结果被缓存,即使后端数据库数据已删除,前端仍会读取缓存中的旧数据。而Postman默认不会缓存请求结果,所以能拿到最新的接口响应。

解决方案

1. 禁用fetch缓存

直接给fetch添加cache: 'no-store'选项,强制每次请求都拉取最新数据:

async function loadImg(){
  const res = await fetch("http://localhost:4000/api/getImages", {
    cache: 'no-store'
  })
  const data = await res.json()
  return data
}

2. 启用即时重新验证

如果需要保留部分缓存能力但确保数据实时更新,可以使用next.revalidate: 0配置:

async function loadImg(){
  const res = await fetch("http://localhost:4000/api/getImages", {
    next: { revalidate: 0 }
  })
  const data = await res.json()
  return data
}

3. 排除浏览器缓存干扰

可以尝试强制刷新页面(Ctrl+F5),清除浏览器层面的缓存,确保测试的是最新的请求结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:35:09