Next.js API路由返回404错误。

huangapple go评论73阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2023年7月10日 22:48:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定