route.js
路由處理器讓您可以使用 Web Request 和 Response API,為給定的路由建立自訂請求處理器。
route.ts
export async function GET() {
return Response.json({ message: 'Hello World' })
}
參考
HTTP 方法
路由檔案讓您能為給定的路由建立自訂請求處理器。支援下列 HTTP 方法:GET
、POST
、PUT
、PATCH
、DELETE
、HEAD
和 OPTIONS
。
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
}
範例 | 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'] }> |
範例
處理 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')
}
版本歷史
版本 | 變更 |
---|---|
v15.0.0-RC | context.params 現在是一個 Promise。有一個 codemod 可用 |
v15.0.0-RC | GET 處理器的預設快取已從靜態變更為動態 |
v13.2.0 | 引入路由處理器。 |
這有幫助嗎?