我在 Next.js 中有这个路由处理程序:
export async function GET(_: Request, { params: { statusId } }: Params) {
const tweetResponse = await queryClient<
Tweet & Pick<User, "name" | "userImage" | "tag">
>(`/tweets/${statusId}`, {
cache: "no-store",
});
if (!tweetResponse.success) {
if (tweetResponse.status === 404) notFound();
throw new Error(tweetResponse.message);
}
const { tag, tweetId } = tweetResponse.data;
redirect(`/${tag}/status/${tweetId}`);
}
如果找到该推文,它将重定向到正确的页面。但如果不是,那么该函数应该抛出 404(如调用 notFound() 函数所示)。
问题是,Next.js 确实返回 404,但它不显示我的自定义 404 页面。事实上,它根本不显示 404 页面,不是我自定义的页面,也不是默认的 next.js 页面,相反,浏览器甚至找不到要显示的页面,所以它只是说“在地址处找不到网页”
如何解决这个问题?我只需要显示404页面(
not-found.tsx
中定义的自定义页面)
我就遇到了这种情况。使用路由处理程序调用
notFound()
只会向客户端组件返回 404。您需要做的是 try/catch
API 调用并手动重定向到 /not-found
。
类似:
try {
const response = await axios.get(`/api/tweets/${tweetId}`);
} catch (e) {
router.push('/not-found');
}