Next.js中getServerSideProps无法获取数据问题求助
问题排查与解决方案
针对你用Next.js的getServerSideProps获取数据返回空对象/undefined的问题,按以下步骤排查:
先验证请求是否成功
很多时候问题出在请求本身失败(比如API限流、网络问题),但你没做错误处理。在fetch后添加状态码检查:export const getServerSideProps = async () => { const res = await fetch(`https://rickandmortyapi.com/api/character`) // 检查请求状态 if (!res.ok) { console.error(`请求失败,状态码:${res.status}`) return { props: { data: null } } } const data = await res.json() console.log(data) return { props: { data } } }注意控制台输出的位置
getServerSideProps是在服务器端执行的,你在浏览器控制台看不到它的console.log输出,得去启动Next.js项目的终端里查看。如果之前一直看的是浏览器控制台,自然会误以为数据是空的。确认页面组件正确接收Props
确保页面组件正确解构传入的props,否则在客户端会拿到undefined:// 页面组件示例 export default function CharacterPage({ data }) { // 这个console.log会出现在浏览器控制台 console.log('客户端接收的数据:', data) return <div>{data ? JSON.stringify(data) : '数据加载失败'}</div> }检查Next.js版本与路由模式
如果你用的是Next.js 13+的App Router,getServerSideProps是不支持的。这种情况要改用Server Component直接写异步逻辑,模拟getServerSideProps的实时请求行为需添加cache: 'no-store':// app/[page]/page.js async function CharacterPage() { const res = await fetch(`https://rickandmortyapi.com/api/character`, { cache: 'no-store' }) if (!res.ok) { throw new Error('获取数据失败') } const data = await res.json() return <div>{JSON.stringify(data)}</div> } export default CharacterPage
内容的提问来源于stack exchange,提问作者user18373410
相关产品推荐
相关产品推荐

