英文:
Next.js api router throws 404
问题
我是新手使用Next.js,我在让我的API正常工作方面遇到了问题。我已经在src/app/api/hello.ts
上设置了一个测试端点,它有一个基本的响应。然而,当我尝试访问example.com/api/hello
时,我得到了一个404页面,而不是预期的响应。有谁可以帮助我排除这个问题?以下是我的端点的代码:
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
注意:我使用auth0进行身份验证,/api/auth/[auth0]/
工作得很好。
英文:
I am new to Next.js and I'm having trouble getting my API to work properly. I've set up a test endpoint at src/app/api/hello.ts
with a basic response. However, when I try to access example.com/api/hello
, I'm getting a 404 page instead of the expected response. Can anyone help me troubleshoot this issue? Here's the code for my endpoint:
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
Note: I use auth0 for authentication and the /api/auth/[auth0]/
works just fine.
答案1
得分: 1
看起来你正在使用 Next.js 13 的新 应用路由器。当使用应用路由器与 API 路由一起时,你需要遵循 API 路由的命名约定:app/api/[ROUTE_PATH]/route.ts
。所以尝试将你当前路由处理程序的内容移动到 src/app/api/hello/route.ts
。使用新的应用路由器,路由处理程序的 签名 也发生了变化:不再是默认导出一个处理程序,而是需要为路由支持的每个 HTTP 方法(例如 GET、POST、PUT 等)导出一个函数,该函数接受一个类型为 Request
的单一参数。希望这对你有帮助!
英文:
It seems like you are using the new app router of next.js 13. When using app router with api routes, you have to follow the naming convention for api routes: app/api/[ROUTE_PATH]/route.ts
. So try to move the contents of your current route handler to src/app/api/hello/route.ts
. Using the new app router, the signature of the route handler changed as well: instead of one handler exported as default, you will have to export a function for each HTTP method your route supports (e.g. GET, POST, PUT, ...), which accepts a single parameter of type Request
. I hope this helped you!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论