使用Nextjs时如何检查用户是否转到有效路线

问题描述 投票:0回答:1

我有一个问题,过去 2 小时我在网上寻找答案,但没有找到。

我正在将 Nextjs 与新的应用程序路由器一起使用。 当用户导航到 app/api 中未定义的路线时。
例如:

(localhost:3000/api/useer/1235)
(userr=不存在) 接下来将响应 404 html 页面,这是正确的,
但不是返回 html 页面,因为它是
api call
,我想向用户返回
Json response

任何帮助或建议表示感谢,谢谢。

reactjs next.js next.js13 app-router
1个回答
0
投票

您可以使用 Catch All API 路由/可选 Catch All API 路由来处理所有不存在的请求。实际存在的请求页面将优先于该路由,因此它不会干扰您现有的 API 路由。

https://nextjs.org/docs/pages/building-your-application/routing/api-routes#catch-all-api-routes

pages/api/post/[...slug].js 匹配 /api/post/a,但也匹配 /api/post/a/b、/api/post/a/b/c 等等。

然后将您想要的任何 JSON 响应放入其中。

© www.soinside.com 2019 - 2024. All rights reserved.