Cloudflare Workers Playground API 完全指南:Handler、Request、Response 与边缘运行时核心能力
【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills
Cloudflare Workers Playground 是一个无需注册、无需安装 CLI、打开浏览器即可直接编写并运行 Worker 代码的在线沙箱,代码运行在真实的 Cloudflare Workers 运行时上。本文以 Playground 的 API 参考文档为主体,系统讲解 Worker 的 fetch Handler 入口、Request/Response 处理、ExecutionContext 后台任务、fetch 子请求、Cache 缓存与 Crypto 加密等核心能力,并对照 Playground 的资源限制与常见坑点,帮助你在几分钟内写出可直接复制运行的边缘代码原型。
一次调用,理解全部入口:fetch Handler
在 Workers Playground 中,代码必须使用 ES Modules 格式,并默认导出一个包含fetch方法的对象。fetch是该 Worker 的唯一天然入口:每当有 HTTP 请求命中你的 Worker 时,运行时都会调用它,并把(request, env, ctx)三个参数传进来。
export default { async fetch(request, env, ctx) { // request: Request, env: {} (empty in playground), ctx: ExecutionContext return new Response('Hello'); } };三个参数的分工如下:
| 参数 | 类型 | 作用 |
|---|---|---|
request | Request | 描述进入的 HTTP 请求,包含 method、URL、headers、body 等 |
env | object | 绑定对象与环境变量容器;在 Playground 中恒为{}(无 KV/D1/R2 等绑定) |
ctx | ExecutionContext | 提供waitUntil()/passThroughOnException()等请求生命周期控制 |
Playground 语法要点(与 configuration.md 中的约束一致):
- 必须使用 ES Modules 语法(
export default),不支持 Service Worker 旧格式; - 仅支持纯 JavaScript,TypeScript 需要先构建,因此 Playground 内不可用;
fetch必须返回Response对象,否则运行时抛错;- 依赖可以从 CDN 直接 import,例如
import { Hono } from 'https://esm.sh/hono@3'。
Request:读取请求的一切
进入 Handler 的request对象封装了客户端请求的全部信息。核心读取方式如下:
const method = request.method; // "GET", "POST" const url = new URL(request.url); // Parse URL const headers = request.headers; // Headers object const body = await request.json(); // Read body (consumes stream) const clone = request.clone(); // Clone before reading body // Query params url.searchParams.get('page'); // Single value url.searchParams.getAll('tag'); // Array // Cloudflare metadata request.cf.country; // "US" request.cf.colo; // "SFO"三个易踩的细节
- Body 只能读一次:
request.json()、request.text()、request.formData()、request.arrayBuffer()都会消费请求体流。如果后续还要用 body 发起 fetch,必须先request.clone(),否则会触发 "Response body already read" 运行时错误(详见 gotchas.md):
// ❌ Body consumed twice const body = await request.text(); await fetch(url, { body: request.body }); // Error! // ✅ Clone first const clone = request.clone(); const body = await request.text(); await fetch(url, { body: clone.body });Query 参数用 URL API 解析:
new URL(request.url)后使用searchParams.get()取单值、searchParams.getAll()取数组(例如?tag=a&tag=b)。request.cf是 Cloudflare 附加元数据:包含country(访问者国家代码)、colo(命中的数据中心三字码,如"SFO")等网络属性,可用于地域分流等边缘逻辑。这是 Playground 与本地fetch的最大差异之一——本地环境没有cf数据。
Response:构造所有输出
Handler 返回的Response支持文本、JSON、重定向以及对已有响应的修改。Playground 运行时完整支持 Fetch API 的 Response 规范:
// Text return new Response('Hello', { status: 200 }); // JSON return Response.json({ data }, { status: 200, headers: {...} }); // Redirect return Response.redirect('/new-path', 301); // Modify existing const modified = new Response(response.body, response); modified.headers.set('X-Custom', 'value');用法详解
new Response(body, init):init可传status、statusText、headers;body 可以是字符串、Uint8Array、ReadableStream或null(用于 204/304 等空响应)。Response.json(data, init):便捷构造 JSON 响应的静态方法,自动设置Content-Type: application/json。构造 API 响应时优先用它,可省去手动JSON.stringify+ 手动设头(参考 patterns.md 的 JSON API 示例)。Response.redirect(url, status):重定向通常使用301(永久)或302(临时);也可用相对路径/new-path,运行时会在发送前拼接为完整 URL。- 修改既有响应:
new Response(response.body, response)会把原响应作为 init 模板复制出可写的新响应,随后用modified.headers.set(...)追加自定义头。这是代理/网关场景下给上游响应注入X-Custom、CORS 头时的标准做法:
// CORS 代理中为上游响应注入跨域头 const response = await fetch('https://api.example.com', request); const modified = new Response(response.body, response); modified.headers.set('Access-Control-Allow-Origin', '*'); return modified;注意:修改响应必须复制出一个新Response,直接在原响应上headers.set()会报错(原响应头只读)。可参考 workers/api.md 中 Cache API 对同一手法的使用。
ExecutionContext:把慢工作放到响应之后
ctx是第三个参数,它管理请求的生命周期。最重要的方法是waitUntil():它接受一个 Promise,让 Worker 在响应返回之后继续执行后台任务,且不影响响应延迟。
// Background work (after response sent) ctx.waitUntil(fetch('https://logs.example.com', { method: 'POST', body: '...' })); return new Response('OK'); // Returns immediately为什么必须用 waitUntil
Playground(以及生产 Workers)的 CPU 时间限制非常紧张(Free 计划 10ms)。如果同步await一个耗时的日志上报或分析调用,会占用请求的主 CPU 时间,可能直接触发 "Worker exceeded CPU time" 错误。把这类工作丢进waitUntil后,return new Response('OK')会立即返回,后台任务在请求结束后继续完成(见 gotchas.md 的对应示例)。
// ✅ Move slow work to background ctx.waitUntil(fetch('https://analytics.example.com', {...})); return new Response('OK'); // Return immediately此外,workers/api.md中还提到ctx.passThroughOnException()(Handler 抛错时放行到源站)——不过在 Playground 这种无源站的场景中意义有限,生产环境(配合wrangler)才常用。
Fetch:在边缘发起子请求
Worker 内可以使用标准fetchAPI 请求任意外部服务,返回的同样是一个Response。这是 Playground 中搭建 API 聚合、代理、鉴权网关的基础:
const response = await fetch('https://api.example.com'); const data = await response.json(); // With options await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Alice' }) });典型用法:透明代理
patterns.md 给出了一种极简代理写法——改写url.hostname后把原请求原样转发:
export default { async fetch(request) { const url = new URL(request.url); url.hostname = 'api.example.com'; return fetch(url.toString(), { method: request.method, headers: request.headers, body: request.body }); } };计数提示
每个出站 fetch 算作一次subrequest(子请求),Playground 上限为 50 次/请求。循环发 100 个请求会触发 "Too many subrequests" 错误,应改为批量聚合(如一次 POST 携带多个 id)。该限制详见下文「Limits」一节与 gotchas.md。
Cache:用 caches.default 做边缘缓存
Playground 暴露了 Cache API 的默认缓存区caches.default,可在请求层实现简单的读-写缓存:
const cache = caches.default; // Check cache let response = await cache.match(request); if (!response) { response = await fetch(origin); await cache.put(request, response.clone()); // Clone before put! } return response;两个关键点:
cache.put之前必须response.clone():put会消费响应体流,直接传入response会把它变成"已读"状态,导致随后的return response抛错。- 只在可缓存的场景使用:实际生产代码通常还会校验
request.method === 'GET'与response.status === 200,再决定是否写入缓存(见 patterns.md 的完整 Caching 示例)。workers/api.md中还展示了配合ctx.waitUntil(cache.put(...))异步写入、避免占用响应路径时间的写法。
Crypto:浏览器级 Web Crypto 直接可用
Playground 运行时内置 Web Crypto API,可生成 UUID、随机字节与哈希摘要,无需引入任何第三方库:
crypto.randomUUID(); // UUID v4 crypto.getRandomValues(new Uint8Array(16)); // SHA-256 hash const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data));crypto.randomUUID():生成 UUID v4 字符串,适合作为请求 ID、幂等键或临时标识。crypto.getRandomValues():填充密码学安全的随机字节,注意必须传入Uint8Array等整数类型数组。crypto.subtle.digest():计算哈希(支持 SHA-1、SHA-256、SHA-384、SHA-512),返回ArrayBuffer。由于digest接收的是字节序列,字符串需先经TextEncoder().encode()转换——这是最常见的遗忘点。
Limits:Playground 即 Free Plan
Playground 的资源限制与生产环境Free 计划完全一致,这是所有原型设计必须牢记的边界:
| Resource | Limit |
|---|---|
| CPU time | 10ms |
| Subrequests | 50 |
| Memory | 128 MB |
补充自 configuration.md 的完整限制表:
| Resource | Limit | Notes |
|---|---|---|
| CPU time | 10ms | Per request |
| Memory | 128 MB | Per request |
| Script size | 1 MB | After compression |
| Subrequests | 50 | Outbound fetch calls |
| Request size | 100 MB | Incoming |
| Response size | Unlimited | Outgoing (streamed) |
面对限制的实战对策
- CPU 超限:超出会立即抛错。把重活交给
ctx.waitUntil后台执行、减少不必要的循环与同步计算;生产可升级 Paid 计划获得 50ms CPU(见 gotchas.md)。 - 子请求超限:50 次以内,优先批量聚合出站调用(一次请求取回多条数据)。
- 内存 128 MB:避免把大响应整体读入内存,优先用流式处理。
从 Playground 到生产:必须注意的差异
Playground 是快速原型工具,不等价于生产环境(详见 README.md 的对比表)。迁移到生产前需要明确以下差异:
| Feature | Playground | Production (wrangler) |
|---|---|---|
| Language | JavaScript only | JS + TypeScript |
| Bindings | None | KV, D1, R2, DO, AI, etc. |
| Environment vars | None | Full support |
| Module format | ES only | ES + Service Worker |
| CPU time | 10ms (Free plan) | 10ms Free / 50ms Paid |
| Custom domains | No | Yes |
| Analytics | No | Yes |
这意味着:Playground 中env永远是{},无法读取密钥或绑定数据库;request.cf之外的平台能力(KV、D1、R2、Durable Objects 等)均不可用。原型验证通过后,应使用wranglerCLI 部署正式 Worker,再按需添加 bindings、自定义域名与环境变量(部署流程与账号相关细节见 configuration.md)。
常见运行时错误速查
| 错误 | 原因 | 对策 |
|---|---|---|
| "Response body already read" | body 流被消费两次 | 先用request.clone()/response.clone()再复用 |
| "Worker exceeded CPU time" | 超出 10ms(Free)/ 50ms(Paid) | 用ctx.waitUntil后台化慢任务,优化热路径 |
| "Too many subrequests" | 出站 fetch 超过 50 次(Free)/ 1000 次(Paid) | 批量聚合为单次 API 调用 |
调试技巧:Playground 支持console.log,可在浏览器 DevTools 的 Console 面板查看输出(右键预览区 → Inspect)。需要留意的是 DevTools 展示的是客户端侧日志,并非 Worker 执行日志;生产环境请使用 Logpush 或 Tail Workers(见 gotchas.md)。
延伸阅读
- Workers Playground 配置与约束:Playground 启动、编辑器语法要求、HTTP 测试面板、共享链接与部署流程
- Workers Playground 常用模式:JSON API、路由分发、代理、CORS、缓存、Hono 框架与鉴权等可直接复用的完整示例
- Workers Playground 常见坑点:平台限制、运行时错误排查与最佳实践
- Workers 运行时 API:生产环境下的完整 API 参考(含 bindings、HTMLRewriter 等 Playground 之外的能力)
- Cloudflare Deploy Skill 总览:按"运行代码/存储数据/AI/网络/安全"决策树选择合适的 Cloudflare 产品
【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考