You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:10:51