Skip to content

定义 API 路由

概念

  • API 路由用于在同一项目内编写后端接口,位于 app 目录下使用 route.ts/route.js 文件实现(替代旧的 pages/api)。

文件与约定

  • 放置位置:app/.../route.ts(或 route.js)。
  • 支持的方法:在同一文件中导出 GET/POST/PUT/DELETE/OPTIONS 等函数,或者导出 export async function handler(req) {} 并检查 req.method
  • 示例文件:
ts
// app/api/hello/route.ts
import { NextResponse } from 'next/server'

export async function GET() {
  return NextResponse.json({ hello: 'world' })
}

export async function POST(req: Request) {
  const data = await req.json()
  return NextResponse.json({ received: data })
}

基于 MIT 许可发布