หัวข้อ 2: Fetch API และการเรียก REST API

คำจำกัดความ

Fetch API คือ Browser API สำหรับส่ง HTTP request และรับ response โดยคืนค่าเป็น Promise ของ Response

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart LR
  A["Client
เว็บเบราว์เซอร์"] --> B["fetch(url, options)
ส่ง Request"] B --> C["REST API
Server Endpoint"] C --> D["Response
status + body"] D --> E["json/text/blob
แปลงข้อมูล"]

Response Methods

Method คืนข้อมูล ใช้กับ
response.json() object/array JSON API
response.text() string HTML, plain text
response.blob() Blob รูปภาพ ไฟล์

GET Request

interface User {
  id: number;
  name: string;
  email: string;
}

async function getUsers(): Promise<User[]> {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");

  // fetch ไม่ throw เมื่อ HTTP status เป็น 404/500 จึงต้องตรวจเอง
  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status}`);
  }

  return response.json();
}

// ตัวอย่างการใช้งาน
getUsers()
  .then(users => console.log(users[0].name))
  .catch(error => console.error(error.message));

POST Request พร้อม Header และ Body

interface CreatePostInput {
  title: string;
  body: string;
  userId: number;
}

async function createPost(data: CreatePostInput) {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer demo-token"
    },
    body: JSON.stringify(data)
  });

  if (!response.ok) {
    throw new Error(`สร้างข้อมูลไม่สำเร็จ: ${response.status}`);
  }

  return response.json();
}

// ตัวอย่างการใช้งาน
createPost({ title: "Hello", body: "Fetch API", userId: 1 })
  .then(post => console.log(post))
  .catch(console.error);

CORS

CORS (Cross-Origin Resource Sharing) คือกลไกความปลอดภัยที่ browser ใช้ควบคุมการเรียก API ข้าม origin

สาเหตุที่มักเจอ:

วิธีแก้เบื้องต้น:

  1. ตั้งค่า server ให้ส่ง Access-Control-Allow-Origin
  2. ใช้ proxy ใน dev server
  3. ตรวจ method/header ที่ browser ส่ง

Axios เบื้องต้น

Axios เป็น library ที่ใช้งานสะดวกกว่า fetch ในหลายกรณี เช่น auto JSON parsing และ interceptor

// ตัวอย่างแนวคิด Axios
// const response = await axios.get<User[]>("/api/users");
// console.log(response.data);

สมการจำนวน Request ทั้งหมด

R = p × n

โดยที่ R คือจำนวน request ทั้งหมด, p คือจำนวนหน้า, และ n คือจำนวน request เฉลี่ยต่อหน้า

แบบทดสอบหลังเรียน

  1. fetch() คืนค่าอะไร
  2. ทำไมต้องตรวจ response.ok
  3. Content-Type: application/json ใช้เพื่ออะไร
  4. CORS เกิดจากอะไร
  5. Axios สะดวกกว่า Fetch ในด้านใด

กลับสัปดาห์ที่ 6