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
แปลงข้อมูล"]
| Method | คืนข้อมูล | ใช้กับ |
|---|---|---|
response.json() |
object/array | JSON API |
response.text() |
string | HTML, plain text |
response.blob() |
Blob | รูปภาพ ไฟล์ |
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));
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 (Cross-Origin Resource Sharing) คือกลไกความปลอดภัยที่ browser ใช้ควบคุมการเรียก API ข้าม origin
สาเหตุที่มักเจอ:
วิธีแก้เบื้องต้น:
Access-Control-Allow-OriginAxios เป็น library ที่ใช้งานสะดวกกว่า fetch ในหลายกรณี เช่น auto JSON parsing และ interceptor
// ตัวอย่างแนวคิด Axios
// const response = await axios.get<User[]>("/api/users");
// console.log(response.data);
โดยที่ R คือจำนวน request ทั้งหมด, p คือจำนวนหน้า, และ n คือจำนวน request เฉลี่ยต่อหน้า
fetch() คืนค่าอะไรresponse.okContent-Type: application/json ใช้เพื่ออะไร