0Pricing
Edge Computing with Cloudflare Workers & Deno · 课时

处理 HTTP 请求

编写一个基础 Worker 来拦截并响应 HTTP 请求,展示其核心功能。

处理 HTTP 请求 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Workers and Web Requests

Cloudflare Workers are powerful tools that sit at the edge of the internet. Think of them as highly efficient gatekeepers for your web traffic.

Their primary job is to intercept incoming HTTP requests, process them using your code, and then send back an appropriate HTTP response.

Understanding the Request

Every time a user's browser interacts with your Worker, it receives a Request object. This object is packed with all the details about the incoming request:

  • URL: The full web address the user tried to reach.
  • Method: The HTTP action, like GET (fetching data) or POST (sending data).
  • Headers: Extra information such as the browser type, cookies, and preferred language.
  • Body: Any data sent with the request, common with POST or PUT methods.

Catching the Fetch Event

Cloudflare Workers use an event listener to 'catch' incoming requests. The fetch event is triggered for every HTTP request that hits your Worker.

The standard entry point for a Worker is an exported object with an async fetch method. This method receives the request object as its first argument.

export default {
  async fetch(request, env, ctx) {
    // Your Worker logic goes here
    // The 'request' object holds all incoming request details
    return new Response("Hello from Worker!");
  }
}

Crafting a Simple Response

After your Worker processes a request, it needs to send back a Response object. This object contains the content and metadata that the user's browser will receive.

A basic Response can be created by simply passing a string of text to its constructor.

export default {
  async fetch(request, env, ctx) {
    const responseText = "Welcome to the edge!";
    return new Response(responseText);
  }
}

Your First 'Hello Worker!'

Let's combine what we've learned to create a simple Worker that says "Hello Cloudflare Worker!" to every incoming request.

This is the fundamental structure you'll use for almost all Cloudflare Workers.

export default {
  async fetch(request, env, ctx) {
    return new Response("Hello Cloudflare Worker!");
  }
}

Peeking at the Request URL

You can access various properties of the request object to get information about the incoming request. For example, request.url gives you the full URL that was requested.

This allows you to create dynamic responses based on the specific path or query parameters a user is trying to reach.

export default {
  async fetch(request, env, ctx) {
    const url = request.url;
    return new Response(`You requested: ${url}`);
  }
}

Responding to GET vs. POST

The request.method property tells you the HTTP method used (e.g., GET, POST, PUT, DELETE). You can use this to provide different logic for different types of requests.

For instance, a GET request might fetch data, while a POST request might submit data for creation.

export default {
  async fetch(request, env, ctx) {
    if (request.method === "GET") {
      return new Response("This is a GET request.");
    } else if (request.method === "POST") {
      return new Response("This is a POST request.", { status: 201 });
    }
    return new Response("Method not allowed.", { status: 405 });
  }
}

Custom Headers and Status

You can customize the Response object further by adding HTTP headers or changing the status code. This is done by passing an options object as the second argument to the Response constructor.

  • Headers: Provide metadata about the response (e.g., Content-Type: text/plain).
  • Status Code: Indicates the outcome of the request (e.g., 200 OK, 404 Not Found).
export default {
  async fetch(request, env, ctx) {
    return new Response("Custom response!", {
      status: 200,
      headers: {
        "Content-Type": "text/plain",
        "X-Worker-Info": "Processed at the Edge"
      }
    });
  }
}

Fetching from an Origin

Often, your Worker will act as a proxy. This means it fetches content from an 'origin server' (your actual website or API backend) and potentially modifies it before sending it to the user.

You can use the global fetch() function, passing it the original request object, to forward the request to another server.

export default {
  async fetch(request, env, ctx) {
    // Fetch the request from the origin server
    const response = await fetch(request);
    // You can modify the response here before returning it
    return response;
  }
}

Worker Response Check

You're building a Cloudflare Worker. Which of the following correctly sets the status code of a response to 404 Not Found?

Recap: Handling HTTP Requests

In this lesson, you learned the core of Cloudflare Workers: how they handle HTTP requests and send back responses.

  • Workers intercept fetch events.
  • The Request object contains all incoming request data.
  • You return a Response object to the user.
  • You can access request details like URL and method.
  • Responses can have custom status codes and headers.
  • Workers can act as proxies, fetching content from origin servers.

Next, you'll learn the steps to deploy your first Worker to Cloudflare's edge network so it can start serving users globally!

常见问题解答

「处理 HTTP 请求」课时是免费的吗?

是的 — 「处理 HTTP 请求」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。

「处理 HTTP 请求」这节课中我会学到什么?

编写一个基础 Worker 来拦截并响应 HTTP 请求,展示其核心功能。 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「处理 HTTP 请求」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?

能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设置 Worker 环境
  2. 处理 HTTP 请求
  3. 部署您的第一个 Worker
  4. Workers 中的环境变量与秘密信息
← 返回 Edge Computing with Cloudflare Workers & Deno