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

การผสานเฟรมเวิร์กส่วนหน้า

ผสาน Workers เข้ากับเฟรมเวิร์กส่วนหน้ายอดนิยม เช่น React, Vue หรือ Svelte เพื่อสร้างแอปพลิเคชันฟูลสแตกแบบไดนามิก

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

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

Full-Stack Edge with Frontend Apps

Welcome to integrating frontend frameworks with Cloudflare Workers! This lesson explores how popular frameworks like React, Vue, or Svelte can work seamlessly with Workers to create dynamic, full-stack applications at the edge.

By combining them, you get the best of both worlds: a rich user interface and a super-fast, globally distributed backend.

How Frontends Talk to Workers

At its core, a frontend framework (running in the user's browser) communicates with a Cloudflare Worker using standard HTTP requests. The Worker acts as a lightweight API backend.

  • The frontend sends requests (GET, POST, etc.) to the Worker's URL.
  • The Worker processes the request and returns a response, often JSON data.
  • The frontend then updates the UI based on this data.

Worker: A Simple JSON API

Let's see a basic Worker that acts as a simple API, returning a JSON message. Your frontend application can easily fetch data from this endpoint.

Try running this example to see the Worker's response.

export default {
  async fetch(request, env, ctx) {
    const data = {
      message: "Hello from the Edge!",
      timestamp: new Date().toISOString()
    };

    return new Response(JSON.stringify(data), {
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

Frontend: Making a GET Request

From your frontend app (e.g., a React component), you'd use the browser's fetch API or a library like Axios to call your Worker. Here's how it generally looks (conceptual code, not runnable on its own):

fetch('/api/hello') .then(response => response.json()) .then(data => console.log(data));

The frontend sends a GET request to the Worker, which then sends back the JSON data.

Worker: Handling POST Requests

Frontends often send data to the backend using POST requests, for example, when submitting a form or creating a new item. The Worker can read the request body to get this data.

Run this Worker and imagine your frontend sending a POST request with {"name": "Coddy"} in the body.

export default {
  async fetch(request, env, ctx) {
    if (request.method === 'POST') {
      try {
        const body = await request.json();
        const name = body.name || 'Guest';
        return new Response(JSON.stringify({ greeting: `Hello, ${name}!` }), {
          headers: { 'Content-Type': 'application/json' }
        });
      } catch (error) {
        return new Response('Invalid JSON body', { status: 400 });
      }
    }
    return new Response('Please send a POST request.', { status: 405 });
  }
}

Understanding CORS for Edge APIs

CORS (Cross-Origin Resource Sharing) is a security feature that browsers use. If your frontend (e.g., myapp.com) tries to fetch data from a Worker on a different origin (e.g., myworker.workers.dev), the browser will block it unless the Worker explicitly allows it.

You need to add specific HTTP headers to your Worker's responses to enable CORS.

Implementing Basic CORS in a Worker

To allow your frontend to communicate with your Worker, include CORS headers in your Worker's responses. The Access-Control-Allow-Origin header is crucial.

This example shows how to add basic CORS headers, allowing requests from any origin (*). For production, specify your frontend's exact domain.

export default {
  async fetch(request, env, ctx) {
    const headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*', // Allow requests from any origin
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type'
    };

    if (request.method === 'OPTIONS') {
      // Handle preflight requests for CORS
      return new Response(null, { headers });
    }

    const data = { message: 'CORS enabled response!' };
    return new Response(JSON.stringify(data), { headers });
  }
}

Environment Variables & Secrets

Your Workers might need access to API keys or other sensitive configuration. Use environment variables (often called 'bindings' in Workers) to securely provide these.

Never embed secrets directly in your code or expose them to the frontend. Workers can access these securely at runtime, acting as a proxy for sensitive operations.

  • Define variables in wrangler.toml.
  • Access them via the env object in your Worker.

Best Practices for Integration

To build robust full-stack edge applications, consider these best practices:

  • API Versioning: Use paths like /api/v1/users for easier updates.
  • Clear Endpoint Naming: Make your Worker routes intuitive (e.g., /products, /orders).
  • Error Handling: Return meaningful HTTP status codes (400, 401, 404, 500) and JSON error messages from your Worker.
  • Authentication: Workers can handle authentication tokens (JWTs) and manage user sessions for your frontend.

Quick Check: Worker Integration

When integrating a frontend framework with a Cloudflare Worker, what is the primary mechanism for the frontend to retrieve dynamic data from the Worker?

Recap: Full-Stack Edge Integration

In this lesson, we explored how to integrate frontend frameworks with Cloudflare Workers. We learned that Workers act as powerful, globally distributed API backends that your frontend apps can communicate with via standard HTTP requests.

Key takeaways:

  • Workers serve JSON data and handle various request methods.
  • CORS headers are essential for cross-origin communication.
  • Best practices include clear API design and secure secret management.

This integration allows you to build fast, scalable full-stack applications at the edge!

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

บทเรียน “การผสานเฟรมเวิร์กส่วนหน้า” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การผสานเฟรมเวิร์กส่วนหน้า”

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

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

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

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

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

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

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

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

  1. Workers Sites และ Pages
  2. การผสานเฟรมเวิร์กส่วนหน้า
  3. พร็อกซีฐานข้อมูลด้วย Deno
  4. การเรนเดอร์ฝั่งเซิร์ฟเวอร์ที่เอดจ์
← กลับไปที่ Edge Computing with Cloudflare Workers & Deno