Next.js中getServerSideProps未跳转404而是显示空白页求助
问题分析与解决方案
你的核心问题在于:外部API返回404时,你错误地通过Next.js的res.statusCode判断状态,但这个res是Next.js用来向客户端返回响应的对象,和外部API的响应状态无关,所以你的判断逻辑永远不会触发,导致商品不存在时页面因缺少props显示空白。
正确处理步骤
1. 先修正getProductDetail函数
确保它能正确识别外部API的404响应,要么抛出明确错误,要么返回标识商品不存在的结构:
async function getProductDetail(slug: string) { const apiRes = await fetch(`https://你的外部API地址/products/${slug}`); // 捕获API的错误响应 if (!apiRes.ok) { if (apiRes.status === 404) { throw new Error('ProductNotFound'); // 或者返回 { product: null, relatedProducts: [] } } throw new Error('FetchProductFailed'); } const data = await apiRes.json(); return { product: data.product, relatedProducts: data.relatedProducts }; }
2. 修改getServerSideProps的判断逻辑
通过捕获错误或检查返回的product是否为空,触发notFound: true:
方案一:捕获错误触发404
export const getServerSideProps: GetServerSideProps = async ({ params }) => { try { const { product, relatedProducts } = await getProductDetail(params?.slug as string); // 额外兜底:如果API返回空商品,也触发404 if (!product) { return { notFound: true }; } return { props: { product, relatedProducts } }; } catch (error) { // 判断是否是商品不存在的错误 if (error instanceof Error && error.message === 'ProductNotFound') { return { notFound: true }; } // 其他错误可返回500状态 return { props: { product: null, relatedProducts: [] }, statusCode: 500 }; } };
方案二:通过返回值判断(如果getProductDetail返回null)
export const getServerSideProps: GetServerSideProps = async ({ params }) => { const { product, relatedProducts } = await getProductDetail(params?.slug as string); if (!product) { return { notFound: true }; } return { props: { product, relatedProducts } }; };
关键说明
- Next.js的
notFound: true会自动渲染pages/404.tsx页面,无需手动跳转。 - 不要混淆外部API的响应状态和Next.js自身的响应对象
res,两者属于不同的请求链路。
内容的提问来源于stack exchange,提问作者monm
相关产品推荐
相关产品推荐

