route.js
路由處理程式允許您使用 Web Request 和 Response API 為指定路由建立自訂請求處理程式。
route.ts
export async function GET() {
return new 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
}
範例 | 網址 | 參數 |
---|---|---|
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'] }> |
範例
處理 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')
}