跳至内容

route.js

路由处理程序允许您使用 Web RequestResponse API 为给定路由创建自定义请求处理程序。

route.ts
export async function GET() {
  return new Response.json({ message: 'Hello World' })
}

参考

HTTP 方法

**路由**文件允许您为给定路由创建自定义请求处理程序。以下 HTTP 方法 受支持:GETPOSTPUTPATCHDELETEHEADOPTIONS

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) {}

参数

request(可选)

request 对象是一个 NextRequest 对象,它是 Web Request API 的扩展。NextRequest 使您可以进一步控制传入请求,包括轻松访问 cookies 和扩展的、已解析的 URL 对象 nextUrl

route.ts
import type { NextRequest } from 'next/server'
 
export async function GET(request: NextRequest) {
  const url = request.nextUrl
}

context(可选)

  • params:一个解析为包含当前路由的 动态路由参数 的对象的 Promise。
app/dashboard/[team]/route.ts
export async function GET(
  request: Request,
  { params }: { params: Promise<{ team: string }> }
) {
  const team = (await params).team
}
示例URLparams
app/dashboard/[team]/route.js/dashboard/1Promise<{ team: '1' }>
app/shop/[tag]/[item]/route.js/shop/1/2Promise<{ tag: '1', item: '2' }>
app/blog/[...slug]/route.js/blog/1/2Promise<{ slug: ['1', '2'] }>

示例

处理 Cookie

route.ts
import { cookies } from 'next/headers'
 
export async function GET(request: NextRequest) {
  const cookieStore = await cookies()
 
  const a = cookieStore.get('a')
  const b = cookieStore.set('b', '1')
  const c = cookieStore.delete('c')
}

版本历史

版本更改
v15.0.0-RCcontext.params 现在是一个 Promise。提供了一个 代码修改
v15.0.0-RCGET 处理程序的默认缓存已从静态更改为动态
v13.2.0引入了路由处理程序。