Next.js API Router返回404错误排查求助
Hey there! Sorry to hear you're stuck with this 404 error on your API endpoint—let's walk through some common fixes that should get your /api/hello route working, especially since your Auth0 routes are already functioning properly.
1. 先检查API路由的文件结构(最可能的问题!)
Next.js的App Router对API路由的结构有严格要求:必须在api/[你的路由名]/文件夹下创建route.ts(或.tsx)文件,而不是直接在api目录下建单个.ts文件。
你当前的文件路径是src/app/api/hello.ts,这是Pages Router的写法,但App Router需要的结构是:
src/ app/ api/ hello/ route.ts // 你的处理逻辑要放在这个文件里
2. 修正API路由的导出方式
App Router的API路由不再使用Pages Router里的handler默认导出,而是需要按HTTP方法导出对应的函数(比如GET、POST等),同时使用Web标准的Request对象和NextResponse来返回结果,而不是NextApiRequest/NextApiResponse。
修正后的route.ts代码应该是这样的:
import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json({ name: 'John Doe' }, { status: 200 }); }
3. 重启开发服务器
Next.js有时候不会自动检测到路由文件结构的变化,尤其是当你调整了文件夹层级之后。试着关掉当前的开发服务器,重新运行npm run dev,然后再访问API路由试试。
4. 确认访问的URL是否正确
- 如果是本地开发,要访问的是
http://localhost:3000/api/hello,而不是直接用example.com(除非你已经部署完成并配置了自定义域名)。 - 如果是已经部署的环境,检查部署平台的构建日志,确认新的API路由是否被正确识别并构建。
5. 排除路由拦截的可能
虽然你的Auth0路由正常,但如果项目里有自定义的middleware.ts文件,或者Auth0的配置有全局路由规则,可能会意外拦截其他API路由。可以临时注释掉middleware.ts的内容,测试一下/api/hello是否能正常访问,排除这个干扰因素。
Most likely the file structure or export method mismatch is causing the 404 here—since your Auth0 routes work, they're already following the App Router's correct conventions. Let me know if any of these steps fix your issue, or if you need to dig into more details!
备注:内容来源于stack exchange,提问作者Dr. Arjen

