Axios请求失败时notFound:true未跳转Next.js内置404页面
问题原因
Axios的特性是:当请求返回4xx(比如404)或5xx这类错误状态码时,不会正常返回响应对象,而是直接抛出异常。你原来的代码里,请求ID11时触发了404,Axios直接报错,导致if (userReq.status === 404)这段代码根本没机会执行,反而因为未捕获异常显示了Next.js的错误页面。
解决方案
用try/catch包裹Axios请求,在catch块里捕获错误,判断是否是404状态码,再返回notFound: true。修改后的代码如下:
import Link from 'next/link'; import axios from 'axios'; export async function getServerSideProps(ctx) { const { id } = ctx.query; try { const userReq = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`); return { props: { user: userReq.data, }, }; } catch (error) { // 判断是否是404错误 if (error.response?.status === 404) { return { notFound: true, }; } // 其他错误可以选择抛出或返回其他处理逻辑 throw error; } } function UserPage({ user }) { return ( <div> <div> <Link href="/"> Back to home </Link> </div> <hr /> <div style={{ display: 'flex' }}> <div> <div> <b>Username:</b> {user.username} </div> <div> <b>Full name:</b> {user.name} </div> <div> <b>Email:</b> {user.email} </div> <div> <b>Company:</b> {user.company.name} </div> <div> <b>Phone:</b> {user.phone} </div> </div> </div> </div> ); } export default UserPage;
补充说明:Next.js 13+版本的Link组件已不再需要passHref属性,所以代码中去掉了这个冗余配置。
内容的提问来源于stack exchange,提问作者Robbyo
相关产品推荐
相关产品推荐

