Next.js 13 App目录下如何根据API响应修改页面状态码?
在Next.js 13 App目录中根据API响应设置页面状态码
步骤1:修改getData函数,返回API状态码和数据
首先需要让getData同时返回接口数据和API响应的状态码,这样页面组件才能依据状态码做对应处理:
import type { PageData } from '../types/cms'; export async function getData(pathSegments: Array<string> = []): Promise<{ status: number; data: PageData | undefined }> { const apiEndpoint = `${process.env.API_URL}${pathSegments.length > 0 ? `/${pathSegments.join('/')}/` : ''}`; const res = await fetch(apiEndpoint, { redirect: 'follow', cache: 'no-store' }); let jsonResponse: PageData | undefined; // 仅当响应成功时解析JSON,避免错误状态下解析失败 if (res.ok) { jsonResponse = await res.json(); } return { status: res.status, data: jsonResponse }; }
步骤2:在页面组件中处理不同状态码
处理404状态
Next.js内置了notFound()函数,调用后会自动返回404状态码,并渲染app/not-found.tsx组件(需提前创建该组件):
import { getData } from '../../lib/getData'; import { notFound } from 'next/server'; type PageProps = { params: { segments: Array<string> | undefined } }; export default async function Page({ params }: PageProps) { const { status, data } = await getData(params.segments); // 处理API返回的404 if (status === 404) { notFound(); } // 数据为空时也返回404 if (!data) { notFound(); } return <MyComponent context={data} />; }
处理其他错误状态码(如403、500)
若需返回404以外的错误状态码,可通过两种方式实现:
方式1:直接返回NextResponse
在页面组件中检测到错误状态码时,返回NextResponse对象来设置响应状态:
import { getData } from '../../lib/getData'; import { notFound, NextResponse } from 'next/server'; type PageProps = { params: { segments: Array<string> | undefined } }; export default async function Page({ params }: PageProps) { const { status, data } = await getData(params.segments); if (status === 404) { notFound(); } // 处理400及以上的错误状态码 if (status >= 400) { // 返回对应状态码的自定义响应内容 return new NextResponse(JSON.stringify({ error: 'API请求失败' }), { status, headers: { 'Content-Type': 'application/json' }, }); } if (!data) { notFound(); } return <MyComponent context={data} />; }
方式2:抛出错误并通过error.tsx渲染自定义页面
如果需要展示自定义错误页面,可以抛出带有状态码的错误,再在app/error.tsx组件中捕获处理:
- 在
page.tsx中抛出错误:
import { getData } from '../../lib/getData'; import { notFound } from 'next/server'; type PageProps = { params: { segments: Array<string> | undefined } }; export default async function Page({ params }: PageProps) { const { status, data } = await getData(params.segments); if (status === 404) { notFound(); } if (status >= 400) { const error = new Error(`API返回状态码:${status}`); // 给错误对象添加statusCode属性,方便error.tsx读取 (error as any).statusCode = status; throw error; } if (!data) { notFound(); } return <MyComponent context={data} />; }
- 创建
app/error.tsx组件:
'use client'; export default function Error({ error, reset }: { error: Error & { statusCode?: number }, reset: () => void }) { return ( <div className="container"> <h1>请求出错</h1> <p>状态码:{error.statusCode || 500}</p> <p>错误信息:{error.message}</p> <button onClick={reset}>重新加载</button> </div> ); }
当页面抛出错误时,Next.js会自动将响应状态码设置为错误对象中的statusCode,并渲染error.tsx组件。
内容的提问来源于stack exchange,提问作者Konstantinos Alexis
相关产品推荐
相关产品推荐

