我正在NextJS Repo中为位于以下URL的动态路由运行示例:
https://github.com/vercel/next.js/tree/canary/examples/dynamic-routing
运行应用程序时,我浏览到URL:
http://localhost:3000/about
它工作正常,并显示状态为200的良好页面。
当我浏览到http://localhost:3000/aboutBADROUTE
正如我所料,我得了404分。
然而,这是目前正确的路线:
http://localhost:3000/post/first(返回200(
但是,这:http://localhost:3000/post/firstBADROUTE
还返回200,这不是我想要的。我希望它也能返回404。
我误解了什么?
因为它是动态路由段(https://nextjs.org/docs/routing/introduction#dynamic-路段(
当您访问/about
时,它会返回200,因为您有/pages/about.js
当您访问/aboutBADROUTE
时,它会返回404,因为您没有任何页面与该路由匹配。
当您访问/post/first
或/post/firstBADROUTE
时,它将与此匹配:
post/:id
(所以first
或firstBADROUTE
仍然被认为是id
(
所以当您访问/post/whatevervalue
时,它总是返回200。
在您的情况下,您可以检查它是否是有效的id
,您可以显示正常页面,如果它是无效的id
,则可以显示错误页面(https://nextjs.org/docs/advanced-features/custom-error-page#reusing-内置错误页面(
答案是在结果中包含notFound。这需要在getStaticProps中进行一些工作,但我经常认为这些工作是必要的。
这里有一个关于它的讨论链接。这就是我一直在寻找的答案。
https://github.com/vercel/next.js/discussions/10960#discussioncomment-116705