Next.js中getServerSideProps调用Fake Store API时product显示undefined
解决Next.js getServerSideProps中product显示undefined的问题
你的代码存在一个关键错误:axios会自动解析JSON格式的响应,不需要手动调用res.json()(这是原生fetch API的用法)。axios请求返回的响应对象中,接口返回的数据保存在res.data属性里,当前写法会导致product变量赋值失败,最终传递给组件的props为undefined。
修复后的代码
import axios from "axios"; import Products from "./Products"; const ProductCard = ({ product }) => { console.log(product); return ( <div className=""> <Products product={product} /> </div> ); }; export async function getServerSideProps(context) { const res = await axios.get("https://fakestoreapi.com/products"); // 直接取res.data,axios已自动完成JSON解析 const product = res.data; return { props: { product: product, }, }; } export default ProductCard
额外优化建议
接口返回的是商品数组,建议给变量改个语义更清晰的名字,比如products,同时对应调整组件的props参数:
// 组件参数改为products const ProductCard = ({ products }) => { console.log(products); return ( <div className=""> <Products products={products} /> </div> ); }; export async function getServerSideProps(context) { const res = await axios.get("https://fakestoreapi.com/products"); const products = res.data; return { props: { products: products, }, }; }
内容的提问来源于stack exchange,提问作者user18259724
相关产品推荐
相关产品推荐

