NextJS 14 API请求数据缓存问题:如何确保数据永不被缓存?
解决NextJS 14.x中数据永不缓存的策略
要确保应用永不缓存该接口数据,从前端请求配置和后端API响应配置两方面入手即可:
1. 前端Fetch请求禁用缓存
NextJS 14的App Router中,fetch默认会对请求进行静态缓存。只需在fetch调用中添加cache: 'no-store'选项,就能强制禁用缓存,每次请求都拉取最新数据:
const response = await fetch( "http://localhost:3000/api/public", { cache: 'no-store' // 强制跳过缓存,每次请求都获取最新数据 } ); if (response.ok) { const responseBody = await response.json(); console.log(responseBody); return responseBody; } }``` 也可以使用NextJS专属的`next: { revalidate: 0 }`配置,效果一致: ```async function fetchdetails() { const response = await fetch( "http://localhost:3000/api/public", { next: { revalidate: 0 } // 0表示永不缓存,每次都重新获取 } ); if (response.ok) { const responseBody = await response.json(); console.log(responseBody); return responseBody; } }``` ## 2. 后端API路由设置缓存控制头 针对自己的NextJS API路由,返回响应时添加禁止缓存的HTTP头,形成双重保险,避免任何中间层(如CDN、浏览器)缓存数据: ```import { NextResponse } from 'next/server'; const data = { "message": "hello world!" } export async function GET() { return NextResponse.json(data, { headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate', 'Pragma': 'no-cache', 'Expires': '0', }, }); }``` 另外,也可以在API路由文件顶部添加以下配置,强制该路由为动态模式,彻底禁用缓存: ```export const dynamic = 'force-dynamic';``` 内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

