0Pricing
Edge Computing with Cloudflare Workers & Deno · 강의

HTTP 요청 처리하기

HTTP 요청을 가로채고 응답하는 기본 Worker를 작성하며 핵심 기능을 익힙니다.

HTTP 요청 처리하기은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 요청 처리하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.

“HTTP 요청 처리하기”에서 뭘 배우나요?

HTTP 요청을 가로채고 응답하는 기본 Worker를 작성하며 핵심 기능을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“HTTP 요청 처리하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Worker 환경 설정하기
  2. HTTP 요청 처리하기
  3. 첫 Worker 배포하기
  4. 워커의 환경 변수 및 비밀값
← Edge Computing with Cloudflare Workers & Deno(으)로 돌아가기