[ PROMPT_NODE_24462 ]
Workers Playground API 参考
[ SKILL_DOCUMENTATION ]
# Workers Playground API
## 处理程序 (Handler)
javascript
export default {
async fetch(request, env, ctx) {
// request: Request, env: {} (playground 中为空), ctx: ExecutionContext
return new Response('Hello');
}
};
## 请求 (Request)
javascript
const method = request.method; // "GET", "POST"
const url = new URL(request.url); // 解析 URL
const headers = request.headers; // Headers 对象
const body = await request.json(); // 读取主体(消耗流)
const clone = request.clone(); // 读取主体前克隆
// 查询参数
url.searchParams.get('page'); // 单值
url.searchParams.getAll('tag'); // 数组
// Cloudflare 元数据
request.cf.country; // "US"
request.cf.colo; // "SFO"
## 响应 (Response)
javascript
// 文本
return new Response('Hello', { status: 200 });
// JSON
return Response.json({ data }, { status: 200, headers: {...} });
// 重定向
return Response.redirect('/new-path', 301);
// 修改现有响应
const modified = new Response(response.body, response);
modified.headers.set('X-Custom', 'value');
## 执行上下文 (ExecutionContext)
javascript
// 后台工作(响应发送后)
ctx.waitUntil(fetch('https://logs.example.com', { method: 'POST', body: '...' }));
return new Response('OK'); // 立即返回
## Fetch
javascript
const response = await fetch('https://api.example.com');
const data = await response.json();
// 带选项
await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
});
## 缓存 (Cache)
javascript
const cache = caches.default;
// 检查缓存
let response = await cache.match(request);
if (!response) {
response = await fetch(origin);
await cache.put(request, response.clone()); // 放入前克隆!
}
return response;
## 加密 (Crypto)
javascript
crypto.randomUUID(); // UUID v4
crypto.getRandomValues(new Uint8Array(16));
// SHA-256 哈希
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data));
## 限制 (Playground = 免费计划)
| 资源 | 限制 |
|----------|-------|
| CPU 时间 | 10ms |
| 子请求 | 50 |
| 内存 | 128 MB |