0Pricing
Edge Computing with Cloudflare Workers & Deno · บทเรียน

การกำหนดเส้นทางและมิดเดิลแวร์

ใช้ไลบรารีกำหนดเส้นทางและรูปแบบมิดเดิลแวร์เพื่อจัดระเบียบและเพิ่มความสามารถให้ Worker API

การกำหนดเส้นทางและมิดเดิลแวร์ เป็นบทเรียน Edge Computing with Cloudflare Workers & Deno ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Edge Computing with Cloudflare Workers & Deno และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

API Routing Essentials

When building APIs, we need a way to direct incoming requests to the correct functions based on their URL path and HTTP method (GET, POST, etc.). This process is called routing.

Think of it like a receptionist for your API. When a request comes in, the router checks its destination and sends it to the right department (your code handler).

Manual Worker Routing

In a Cloudflare Worker, all incoming requests are handled by the fetch event listener. You can manually inspect the request's URL and method to decide what to do.

While possible for simple cases, this approach quickly becomes complex and hard to manage as your API grows.

export default {
  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === '/hello' && request.method === 'GET') {
      return new Response('Hello from manual route!');
    }
    return new Response('Not Found', { status: 404 });
  }
}

Introducing itty-router

To simplify routing, we use lightweight libraries. For Cloudflare Workers, itty-router is a popular choice. It's tiny, fast, and designed for the edge.

It provides a clean, expressive way to define routes and handlers, making your Worker code much more organized.

Basic GET Routes

With itty-router, you can define routes using methods like router.get() for GET requests. Each route takes a path and a handler function.

Let's create a simple Worker that responds to / and /greet.

import { Router } from 'itty-router';

const router = Router();

router.get('/', () => new Response('Welcome to the API!'));
router.get('/greet', () => new Response('Hello there!'));

export default {
  fetch: router.handle
};

Handling All HTTP Methods

itty-router allows you to define routes for specific HTTP methods like .post(), .put(), .delete(), and more.

You can also use .all() to match any HTTP method for a given path, useful for middleware or generic handlers.

import { Router } from 'itty-router';

const router = Router();

router.get('/data', () => new Response('GET data'));
router.post('/data', () => new Response('POST data', { status: 201 }));
router.all('*', () => new Response('Method Not Allowed', { status: 405 }));

export default {
  fetch: router.handle
};

Dynamic Route Parameters

Often, you need to extract dynamic values from the URL, like an item ID or a username. These are called route parameters.

itty-router uses a colon (:) to define parameters in a route path. The values are then available in the handler's request.params object.

import { Router } from 'itty-router';

const router = Router();

router.get('/users/:id', ({ params }) => {
  return new Response(`Fetching user ${params.id}`);
});

export default {
  fetch: router.handle
};

What is Middleware?

Middleware functions are code snippets that run before or after your main route handler. They can modify the request, perform logging, check authentication, or add headers to the response.

They act as a pipeline, allowing you to add common functionalities across multiple routes without duplicating code.

Implementing Simple Middleware

With itty-router, middleware can be added to specific routes or globally. A middleware function receives the request and can return a response (ending the chain) or continue to the next handler.

Let's add a simple logging middleware that runs for every request.

import { Router } from 'itty-router';

const router = Router();

const loggerMiddleware = async (request, event) => {
  console.log(`Request: ${request.method} ${request.url}`);
  // To proceed to the next handler, don't return a Response.
  // If you return a Response, the chain stops.
};

router.all('*', loggerMiddleware);
router.get('/hello', () => new Response('Hello from route!'));

export default {
  fetch: router.handle
};

Chaining Middleware

You can chain multiple middleware functions. Each middleware executes in order. If a middleware doesn't return a response, the next one in the chain (or the final route handler) is called.

This allows for powerful, modular processing of requests, like authentication, data parsing, and logging.

import { Router } from 'itty-router';

const router = Router();

const authMiddleware = async (request) => {
  if (request.headers.get('Authorization') !== 'Bearer token123') {
    return new Response('Unauthorized', { status: 401 });
  }
};

const headerMiddleware = async (request, event) => {
  // Add a custom header to the response later
  event.response = new Response('', { headers: { 'X-Powered-By': 'CoddyKit' } });
};

router.get('/secure', authMiddleware, (request) => {
  return new Response('Access granted!');
});
router.get('/info', headerMiddleware, (request) => {
  return new Response('Info page');
});

export default {
  fetch: async (request, env, ctx) => {
    const response = await router.handle(request, env, ctx);
    // Merge headers from middleware if present
    if (ctx.response && response) {
      for (let [key, value] of ctx.response.headers.entries()) {
        response.headers.set(key, value);
      }
    }
    return response;
  }
};

Routing & Middleware Check

Consider a Cloudflare Worker using itty-router. You want to ensure that all requests to /admin/* paths require an X-Admin-Key header, and if it's missing, return a 403 Forbidden response. Other paths should not be affected.

Recap: Routing & Middleware

You've mastered the fundamentals of organizing your edge API with routing and middleware!

  • Routing directs requests to the right handlers.
  • Libraries like itty-router simplify route definition, including dynamic parameters.
  • Middleware functions enhance requests/responses, adding common logic like logging or authentication before (or after) the main handler.

These patterns are crucial for building scalable and maintainable serverless APIs at the edge.

คำถามที่พบบ่อย

บทเรียน “การกำหนดเส้นทางและมิดเดิลแวร์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การกำหนดเส้นทางและมิดเดิลแวร์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Edge Computing with Cloudflare Workers & Deno ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การกำหนดเส้นทางและมิดเดิลแวร์”

ใช้ไลบรารีกำหนดเส้นทางและรูปแบบมิดเดิลแวร์เพื่อจัดระเบียบและเพิ่มความสามารถให้ Worker API คุณปฏิบัติ Edge Computing with Cloudflare Workers & Deno ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Edge Computing with Cloudflare Workers & Deno หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Edge Computing with Cloudflare Workers & Deno บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน

บทเรียน “การกำหนดเส้นทางและมิดเดิลแวร์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Edge Computing with Cloudflare Workers & Deno นี้ได้ไหม

ได้ บทเรียน Edge Computing with Cloudflare Workers & Deno ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การออกแบบ API แบบ RESTful
  2. การกำหนดเส้นทางและมิดเดิลแวร์
  3. การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด
← กลับไปที่ Edge Computing with Cloudflare Workers & Deno