跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

运行 JavaScript

最后更新 查看 MarkdownAgent 设置

您将向 Worker 发送包含 JavaScript 的 POST 请求,并读取 {"result":["Ada"]}。

前提条件

  1. 注册 Cloudflare 账户 ↗。
  2. 安装 Node.js ↗。

Node.js 版本管理器

使用 Vite+ (vp env) ↗ 安装和管理 Node.js 版本。

有关支持的 Node.js 版本,请参阅 Wrangler 系统要求。

运行 JavaScript

  1. 创建一个 Worker 项目:

    npm create cloudflare@latest -- sandbox-dynamic-worker --category=hello-world --type=hello-world --lang=ts --no-deploy
  2. 进入项目目录:

    cd sandbox-dynamic-worker
  3. 替换 wrangler.jsonc,添加 Worker Loader 绑定:

    {
    	"$schema": "node_modules/wrangler/config-schema.json",
    	"name": "sandbox-dynamic-worker",
    	"main": "src/index.ts",
    	// Set this to today's date
    	"compatibility_date": "2026-11-14",
    	"observability": {
    		"enabled": true,
    	},
    	"upload_source_maps": true,
    	"worker_loaders": [
    		{
    			"binding": "LOADER",
    		},
    	],
    }
    "$schema" = "node_modules/wrangler/config-schema.json"
    name = "sandbox-dynamic-worker"
    main = "src/index.ts"
    # Set this to today's date
    compatibility_date = "2026-11-14"
    upload_source_maps = true
    
    [observability]
    enabled = true
    
    [[worker_loaders]]
    binding = "LOADER"
  4. 为绑定生成类型:

    npx wrangler types
  5. 替换 src/index.ts。您的 Worker 会读取 JSON 正文中的 code,并在沙箱中运行它:

    src/index.jsjs
    export default {
    	async fetch(request, env) {
    		const { code } = await request.json();
    
    		const sandbox = env.LOADER.load({
    			compatibilityDate: "2026-11-14",
    			mainModule: "code.js",
    			modules: {
    				"code.js": `
    					import { WorkerEntrypoint } from "cloudflare:workers";
    
    					export class Code extends WorkerEntrypoint {
    						evaluate() {
    							${code}
    						}
    					}
    				`,
    			},
    			// Block `fetch()` and `connect()`
    			globalOutbound: null,
    			// Stop code that uses more than 50 milliseconds of CPU time
    			limits: { cpuMs: 50 },
    		});
    
    		const result = await sandbox.getEntrypoint("Code").evaluate();
    		return Response.json({ result });
    	},
    };
    src/index.tsts
    import type { WorkerEntrypoint } from "cloudflare:workers";
    
    type CodeEntrypoint = WorkerEntrypoint & {
    	evaluate(): Promise<unknown>;
    };
    
    export default {
    	async fetch(request: Request, env: Env): Promise<Response> {
    		const { code } = (await request.json()) as { code: string };
    
    		const sandbox = env.LOADER.load({
    			compatibilityDate: "2026-11-14",
    			mainModule: "code.js",
    			modules: {
    				"code.js": `
    					import { WorkerEntrypoint } from "cloudflare:workers";
    
    					export class Code extends WorkerEntrypoint {
    						evaluate() {
    							${code}
    						}
    					}
    				`,
    			},
    			// Block `fetch()` and `connect()`
    			globalOutbound: null,
    			// Stop code that uses more than 50 milliseconds of CPU time
    			limits: { cpuMs: 50 },
    		});
    
    		const result = await sandbox
    			.getEntrypoint<CodeEntrypoint>("Code")
    			.evaluate();
    		return Response.json({ result });
    	},
    };

    code 是 evaluate() 的函数体,因此需要包含 return 语句。不占用 CPU 的等待代码仍可能让请求保持打开状态,所以在运行他人提供的代码前,应先设置超时。有关示例,请参阅构建 AI 代码解释器。

  6. 运行 wrangler dev:

    npx wrangler dev
  7. 向 Wrangler 输出的 URL 发送包含 JavaScript 的 POST 请求。默认 URL 为 http://localhost:8787:

    curl http://localhost:8787 --request POST --json '{
      "code": "const users = [{ name: \"Ada\", role: \"admin\" }, { name: \"Grace\", role: \"user\" }]; return users.filter((u) => u.role === \"admin\").map((u) => u.name);"
    }'

响应正文为 {"result":["Ada"]}。Worker 已运行您发送的 JavaScript。

后续步骤

这篇文档对您有帮助吗?