Next.js中getServerSideProps无法传递数据问题求助
解决getServerSideProps传递props为undefined的问题
你的代码里存在一个核心错误,导致properties无法正确获取:
axios的get方法会自动将响应的JSON数据解析为JavaScript对象,所以res.data已经是解析后的结果,不需要再调用.json()方法。当前代码里的await res.data.json()会触发报错(因为res.data不是浏览器原生的Response对象,没有json()方法),最终导致properties变成undefined,组件自然接收不到数据。
修正后的getServerSideProps代码
export const getServerSideProps: GetServerSideProps = async () => { const getActivePropertiesURL = 'http://localhost:9090/property/getAllActiveListings'; const res = await axios.get(getActivePropertiesURL); // 直接使用axios已解析好的res.data const properties = res.data; return { props: { properties, }, }; };
额外检查点
- 确保
getServerSideProps和Gallery页面组件在同一个文件中,它仅能用于Next.js的页面组件(pages目录或app目录的page文件,取决于你的Next.js版本),不能在普通组件中使用。 - 验证后端接口
http://localhost:9090/property/getAllActiveListings确实返回了符合PropertyType定义的JSON数据,可以直接在浏览器或接口测试工具中访问该接口确认返回内容。
内容的提问来源于stack exchange,提问作者Acer79
相关产品推荐
相关产品推荐

