[ PROMPT_NODE_24188 ]
Pages API 参考
[ SKILL_DOCUMENTATION ]
# Functions API
## 基于文件的路由
/functions/index.ts → example.com/
/functions/api/users.ts → example.com/api/users
/functions/api/users/[id].ts → example.com/api/users/:id
/functions/api/users/[[path]].ts → example.com/api/users/* (全匹配)
/functions/_middleware.ts → 在所有路由前运行
**规则**: `[param]` = 单段路径, `[[param]]` = 多段全匹配, 更具体的路由优先级更高。
## 请求处理器
typescript
import type { PagesFunction } from '@cloudflare/workers-types';
interface Env {
DB: D1Database;
KV: KVNamespace;
}
// 所有方法
export const onRequest: PagesFunction = async (context) => {
return new Response('All methods');
};
// 特定方法
export const onRequestGet: PagesFunction = async (context) => {
const { request, env, params, data } = context;
const user = await env.DB.prepare(
'SELECT * FROM users WHERE id = ?'
).bind(params.id).first();
return Response.json(user);
};
export const onRequestPost: PagesFunction = async (context) => {
const body = await context.request.json();
return Response.json({ success: true });
};
// 同样支持: onRequestPut, onRequestPatch, onRequestDelete, onRequestHead, onRequestOptions
## 上下文对象 (Context Object)
typescript
interface EventContext {
request: Request; // HTTP 请求
env: Env; // 绑定 (KV, D1, R2 等)
params: Params; // 路由参数
data: Data; // 中间件共享数据
waitUntil: (promise: Promise) => void; // 后台任务
next: () => Promise; // 下一个处理器
passThroughOnException: () => void; // 错误回退 (高级模式不可用)
}
## 动态路由
typescript
// 单段: functions/users/[id].ts
export const onRequestGet: PagesFunction = async ({ params }) => {
// /users/123 → params.id = "123"
return Response.json({ userId: params.id });
};
// 多段: functions/files/[[path]].ts
export const onRequestGet: PagesFunction = async ({ params }) => {
// /files/docs/api/v1.md → params.path = ["docs", "api", "v1.md"]
const filePath = (params.path as string[]).join('/');
return new Response(filePath);
};
## 中间件
typescript
// functions/_middleware.ts
// 单个
export const onRequest: PagesFunction = async (context) => {
const response = await context.next();
response.headers.set('X-Custom-Header', 'value');
return