Next.js 数据获取问题:API更新后无法重新拉取数据
解决Next.js中Fetch数据不自动更新的问题
你的问题核心在于Next.js对服务器组件(或静态生成页面)的fetch请求有默认缓存策略,仅靠请求头无法覆盖Next.js自身的缓存机制,需要针对性配置fetch的缓存选项。
关键原因
Next.js中,服务器组件的fetch请求默认采用force-cache策略——会将请求结果缓存下来,构建后或首次请求后不再主动重新拉取,这就是你添加Cache-Control头却无效的原因。
解决方案
1. 禁用所有缓存(实时获取最新数据)
在fetch配置中添加cache: 'no-store',强制每次服务器接收到请求时都重新拉取API数据:
async function fetchAllMovies() { try { const fetchOptions = { cache: 'no-store', // 核心配置:禁用Next.js的fetch缓存 headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', }, }; const [newMovies, featureMovies, moviesSeries, moviesAnimation, tvShows] = await Promise.all([ fetch('https://phimapi.com/danh-sach/phim-moi-cap-nhat', fetchOptions).then(res => res.json()), fetch('https://phimapi.com/v1/api/danh-sach/phim-le', fetchOptions).then(res => res.json()), fetch('https://phimapi.com/v1/api/danh-sach/phim-bo', fetchOptions).then(res => res.json()), fetch('https://phimapi.com/v1/api/danh-sach/hoat-hinh', fetchOptions).then(res => res.json()), fetch('https://phimapi.com/v1/api/danh-sach/tv-shows', fetchOptions).then(res => res.json()), ]); return { newMovies, featureMovies, moviesSeries, moviesAnimation, tvShows }; } catch (error) { console.error('Fetch lỗi:', error.message); return { newMovies: [], featureMovies: [], moviesSeries: [], moviesAnimation: [], tvShows: [], }; } }
2. 增量静态再生(兼顾性能与数据新鲜度)
如果不需要实时更新,可设置缓存有效期,到期后Next.js会在后台自动重新拉取数据,用户下次访问时获取最新内容:
const fetchOptions = { next: { revalidate: 300 }, // 每5分钟(300秒)重新验证缓存 headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', }, };
3. Pages Router 场景补充(若使用旧路由系统)
如果你的项目用的是Pages Router,需对应修改数据获取逻辑:
- 若用
getStaticProps,添加revalidate字段实现自动更新:export async function getStaticProps() { const data = await fetchAllMovies(); return { props: data, revalidate: 60, // 每60秒重新生成页面 }; } - 若需要每次请求都获取最新数据,直接改用
getServerSideProps替代getStaticProps。
内容的提问来源于stack exchange,提问作者Toan Minh
相关产品推荐
相关产品推荐

