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

JavaScript GET Request: ใช้ Fetch API ดึงข้อมูลจาก Server

นักพัฒนาบ่อยครั้งต้องดึงข้อมูลจาก API ของตัวเองหรือ third-party บทความนี้พูดถึงการใช้ Fetch API ของ browser สำหรับ GET request

Fetch API คืออะไร?

Fetch API เป็น interface ทำ HTTP requests ไป server จาก web browser (Chrome, Firefox) GET request ส่ง request ไป endpoint บน server แล้วได้ response พร้อม data กลับมา

Types of HTTP Requests

GET เป็นแค่หนึ่งประเภท อื่นๆ: POST (Create), PUT (Update), DELETE (Destroy) = CRUD operations Third-party APIs มักอนุญาตแค่ GET (read-only) เพื่อปกป้องข้อมูล

Fetch API ทำงานอย่างไร?

Fetch API ใช้ Promise-based communication Promise คือ async function ที่ encapsulate logic คืนค่า resolved/rejected เราไม่ต้องเขียน promise logic เอง ใช้ fetch() method ที่ available ใน global scope ส่ง endpoint URL เข้าไป

Syntax แบบ Promise chain:

promise.then(response).then(json).catch(error);

fetch() คืนค่า promise:

let promise = fetch("https://swapi.dev/api/films/1");

2 วิธีจัดการ Response

1. Promise Syntax (then/catch)

promise.then(response => {
  if (response.status !== 200) {
    console.log('Error. Status Code: ' + response.status);
    return;
  }
  response.json().then(data => {
    console.log(data);
  }).catch(error => {
    console.log(error.message);
  });
});

รอ response เช็ค status code 200 แล้ว parse JSON ด้วย json() method chain promise อีกที เพื่อรอ parse เสร็จก่อน log data

2. Async/Await (ทันสมัยกว่า)

let getRequest = async () => {
  try {
    let fetched = await fetch("https://swapi.dev/api/films/1");
    if (fetched) {
      let read = await fetched.json();
      console.log(read);
      return read;
    }
  } catch (error) {
    throw new Error(error.message);
  }
};

getRequest();

async บอกว่ามีส่วน async await pause script จนบรรทัดนั้น evaluate เสร็จ มี 2 await: 1) fetch 2) parse JSON ใช้ try/catch จับ error

หมายเหตุสำคัญ: Node.js Environment

Fetch API ทำงานใน browser environment ถ้าใช้ใน Node.js (เช่น VS Code) ต้องติดตั้ง node-fetch:

npm install node-fetch
// หรือ
yarn add node-fetch

สรุป

Fetch API ทำ GET requests ง่ายด้วย Promise-based system ใช้ then/catch หรือ async/await ทั้งคู่ได้ เลือกตามความชอบ async/await โค้ดอ่านง่ายกว่า