Next.js亚马逊克隆项目:fakestoreapi数据控制台可获取但浏览器无法加载且无报错
问题分析与解决方案
我仔细看了你的代码,发现两个核心问题导致浏览器无法渲染商品数据——VS Code控制台能拿到数据是因为服务器端的console.log输出,但数据没正确传递给页面组件,同时图片配置也存在错误。
1. 服务器端数据获取的返回值错误
在getServerSideProps里,你在fetch的then回调里只执行了console.log(json),但这个回调函数没有返回数据,导致products变量最终是undefined,页面组件根本拿不到任何数据。
修复代码(index.js):
export async function getServerSideProps(context) { const products = await fetch("https://fakestoreapi.com/products") .then((res) => res.json()) .then((json) => { console.log(json); // 保留调试用的打印 return json; // 必须把数据返回给products变量 }) .catch(err => { console.error("获取商品数据失败:", err); return []; // 错误时返回空数组,避免页面崩溃 }); return { props: { products: products || [], // 用空数组替代null,防止map报错 }, }; }
2. Next.js图片配置的错误
你的next.config.js里有两处配置错误:
- 配置项
Images应该是小写的images,Next.js的配置字段是驼峰式小写开头,大写的话配置完全不生效,导致Image组件无法加载外部域名的图片。 domains里的"./public"是无效值,public目录是Next.js默认的静态资源目录,不需要添加到图片域名白名单,直接移除即可。
修复后的next.config.js:
/** @type {import('next').NextConfig} */ const isProd = process.env.NODE_ENV === "production"; const nextConfig = { reactStrictMode: true, images: { // 改为小写的images domains: ["fakestoreapi.com"], // 移除无效的./public assetPrefix: isProd ? "/amazon-clone/" : "", }, }; module.exports = nextConfig;
额外优化建议
- 在
ProductFeed组件中给products设置默认空数组,避免数据未加载时出现潜在错误:
function ProductFeed({ products = [] }) { // 添加默认值 return ( <div> {products.map(({ id, title, price, description, category, image }) => ( <Product key={id} title={title} price={price} description={description} category={category} image={image} /> ))} </div> ); }
- 修正
Product组件中Image的属性拼写:objectfit应该是驼峰式的objectFit,否则属性不生效:
<Image src={image} height={200} width={200} objectFit="contain" alt="product-images" />
做完这些修改后,重启开发服务器,浏览器应该就能正常加载商品数据和图片了。
内容的提问来源于stack exchange,提问作者Imangi
相关产品推荐
相关产品推荐

