Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript Fetch API: คู่มือการส่ง Request

Fetch API เป็นวิธีใหม่ใน JavaScript สำหรับส่ง HTTP Request (Ajax) โดยไม่ต้องติดตั้ง Library เพิ่ม รองรับทุกเบราว์เซอร์สมัยใหม่

GET Request ด้วย Fetch

ใช้ JSONPlaceholder API ทดสอบ

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(json => console.log(json));

ผลลัพธ์:

{
  body: "quia et suscipit...",
  id: 1,
  title: "sunt aut facere...",
  userId: 1
}

อธิบาย

  1. fetch(url) - ส่ง request
  2. .then(response => response.json()) - แปลง response เป็น JSON
  3. .then(json => console.log(json)) - แสดงผล

POST Request ด้วย Fetch

const data = {
  name: "Leslie Tudor",
  email: "leslie.tudor@email.com",
  body: "This is an example post!",
  postId: 1
};

const options = {
  method: "POST",
  body: JSON.stringify(data),
  headers: { "Content-Type": "application/json" }
};

fetch('https://jsonplaceholder.typicode.com/comments', options)
  .then(response => response.json())
  .then(json => console.log(json));

ผลลัพธ์: คืน object พร้อม ID ใหม่ (501)

สำคัญสำหรับ POST/PUT/DELETE

  • ระบุ method ใน options
  • แปลงข้อมูลเป็น JSON ด้วย JSON.stringify()
  • ตั้ง header Content-Type: application/json

Error Handling ด้วย .catch()

fetch('https://jsonplaceholder.typicode.com/comments/999', options)
  .then(response => {
    if (response.ok) {
      return response.json();
    } else {
      return Promise.reject({ statusText: response.statusText });
    }
  })
  .catch(error => console.log("ERROR:", error.statusText));

ผลลัพธ์: "ERROR:", "Not Found"

หลักการ

  1. ตรวจสอบ response.ok (status 200-299)
  2. ถ้า fail → Promise.reject() ส่ง error
  3. .catch() รับ error และจัดการ

สรุป

Fetch API ทำ GET, POST, PUT, DELETE ได้ง่าย ไม่ต้องโหลด library ใช้ Promise chain (.then/.catch) จัดการ async

No