Next.js服务端渲染获取数据返回undefined问题求助
Next.js getServerSideProps调用接口返回undefined的排查方案
1. 修复变量作用域问题(第二个代码的核心错误)
你在try块内部声明的data变量仅在块级作用域内有效,外部的console.log(data)和返回的props根本无法获取到值,必然返回undefined。调整代码将变量提升到try外部:
export async function getServerSideProps(context) { let data; try { const res = await fetch('http://localhost:5000/api/blogpost/view'); data = await res.json(); // 先不解构,先确认完整返回结构 } catch (error) { console.error('请求失败:', error); } console.log('接口返回完整数据:', data); return { props: { blog: data } }; }
2. 验证接口返回结构是否匹配解构逻辑
原代码中const { data } = await res.json()的写法,要求接口必须返回包含data字段的对象(比如{"data": [{"id":1, "title":"xxx"}]})。如果接口直接返回数组或不带data字段的对象,解构出来的data就是undefined。
建议先去掉解构,直接打印完整返回结果,确认结构后再调整取值方式。
3. 处理fetch的非200响应
Fetch API不会因非200状态码自动抛出错误,比如接口返回500、404时,fetch仍会进入正常流程,但res.json()可能得到错误信息而非预期数据。需主动判断响应状态:
export async function getServerSideProps(context) { let data; try { const res = await fetch('http://localhost:5000/api/blogpost/view'); if (!res.ok) { throw new Error(`请求失败,状态码: ${res.status}`); } const responseData = await res.json(); // 兼容接口直接返回数据或嵌套在data字段的情况 data = responseData.data ?? responseData; } catch (error) { console.error('请求失败:', error); data = null; // 可设置默认值避免页面报错 } return { props: { blog: data } }; }
4. 排查服务端的localhost解析问题
getServerSideProps在服务端运行,如果你的Next.js应用是在容器(如Docker)中启动,localhost:5000指向的是容器内部而非宿主机器的后端服务。此时需将请求地址改为宿主机器的IP,或使用容器专属host(比如Docker的host.docker.internal)。
内容的提问来源于stack exchange,提问作者hassan
相关产品推荐
相关产品推荐

