主题
定义 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 })
}