Menu

route.js

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

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

参考

HTTP 方法

route 文件允许你为指定路由创建自定义请求处理程序。支持以下 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) {}
 
// 如果未定义 `OPTIONS`,Next.js 将自动实现 `OPTIONS` 并根据路由处理器中定义的其他方法设置适当的 Response `Allow` header
export async function OPTIONS(request: Request) {}
route.js
export async function GET(request) {}
 
export async function HEAD(request) {}
 
export async function POST(request) {}
 
export async function PUT(request) {}
 
export async function DELETE(request) {}
 
export async function PATCH(request) {}
 
// 如果未定义 `OPTIONS`,Next.js 将自动实现 `OPTIONS` 并根据路由处理器中定义的其他方法设置适当的 Response `Allow` header
export async function OPTIONS(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
}
route.js
export async function GET(request) {
  const url = request.nextUrl
}

context (可选)

app/dashboard/[team]/route.ts
export async function GET(
  request: Request,
  { params }: { params: Promise<{ team: string }> }
) {
  const team = (await params).team
}
app/dashboard/[team]/route.js
export async function GET(request, { params }) {
  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'] }>

示例

处理 cookies

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')
}
route.js
import { cookies } from 'next/headers'
 
export async function GET(request) {
  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引入路由处理器