路由處理常式
全端 app/api/*/route.ts 處理常式、重寫與本機常駐程式代理。
路由處理常式使用 Web Request 和 Response API,在 app 目錄中定義 API 端點。
慣例
app/api/health/route.tsts
export function GET(): Response { return Response.json({ status: "ok" });}匯出 GET、POST、PUT、PATCH、DELETE、HEAD 或 OPTIONS。處理常式會在 text dev、text start 和所有伺服器部署介面卡上,於 middleware 之後執行。使用路由區段設定快取 GET 處理常式。
動態處理常式
app/api/sessions/[id]/route.tsts
export async function GET(_req: Request, { params }: { params: { id: string } }) { const session = await db.sessions.find(params.id); return session ? Response.json(session) : new Response("Not found", { status: 404 });}params 的值會經過解碼。含有編碼斜線或反斜線(%2F、%5C)的路徑會收到 400,因此,可能含有 / 的 ID 應透過查詢參數傳遞,或編碼為 base64url。
串流
回傳 ReadableStream 以傳送伺服器發送事件:
app/api/ticks/route.tsts
export function GET() { let n = 0; const stream = new ReadableStream({ start(c) { setInterval(() => c.enqueue(`data: ${n++}\n\n`), 1000); }, }); return new Response(stream, { headers: { "content-type": "text/event-stream" } });}Rewrite
外部目的地由伺服器代理,因此瀏覽器不會發出跨來源請求。
text.config.tsts
export default defineConfig({ rewrites: [{ source: "/api/opencode/:path*", destination: "http://127.0.0.1:4096/:path*" }],});本機常駐程式代理
使用 proxy 連線至你電腦上的處理程序:
text.config.tsts
export default defineConfig({ proxy: { "/api/opencode": { target: "http://127.0.0.1:4096", changeOrigin: true } },});OpenCode 範本就是透過這種方式連線至本機伺服器。