看react官网在推Next.js
,所以简单学习了解一下
DEMO
使用cna
官方脚手架(13+版本)初始化项目以后目录如下:
可以看出,初始项目只有一个根路由页面page.tsx
,想要增加一个纯粹的api route
可以在app/
目录下创建api/xxx/route.ts
。即可访问api/xxx
接口
export async function GET() {return Response.json({ message: "Hello World" });
}
api接口类型
可以通过定义函数名直接指定接口类型
route.ts
export async function GET(request: Request) {}export async function HEAD(request: Request) {}export async function POST(request: Request) {}export async function PUT(request: Request) {}export async function DELETE(request: Request) {}export async function PATCH(request: Request) {}// If `OPTIONS` is not defined, Next.js will automatically implement `OPTIONS` and set the appropriate Response `Allow` header depending on the other methods defined in the Route Handler.
export async function OPTIONS(request: Request) {}
参数类型
接口函数支持两个入参
import type { NextRequest } from 'next/server'export async function GET(request: NextRequest,{ params }: { params: Promise<{ team: string }> }
) {const { team } = await params
}
request
包括cookies
、query
、body
等request
对象信息
context
context: {params: Promise<[x: string]: any>}
params
是一个Promise
类型的动态路由参数对象
Example | URL | params |
---|---|---|
app/dashboard/[team]/route.js | /dashboard/1 | Promise<{ team: ‘1’ }> |
app/shop/[tag]/[item]/route.js | /shop/1/2 | Promise<{ tag: ‘1’, item: ‘2’ }> |
app/blog/[…slug]/route.js | /blog/1/2 | Promise<{ slug: [‘1’, ‘2’] }> |
详细配置参考
- https://nextjs.org/docs/app/building-your-application/routing/route-handlers
- https://nextjs.org/docs/app/api-reference/file-conventions/route