ရိုးရိုးလေး ရှင်းပြမယ်
Fetch API ကို ရိုးရိုးလေး ပြောရရင်
fetch() က URL တစ်ခုဆီ HTTP request ပို့ပြီး Response object တစ်ခုနဲ့ resolve ဖြစ်တဲ့ Promise ကို ပြန်ပေးတဲ့ built-in function ပါ။ Browser တိုင်းမှာ ပါပြီး Node.js 18 ကစပြီး Node မှာလည်း global အနေနဲ့ ပါလာပါတယ်၊ ဒါကြောင့် package install လုပ်စရာ မလိုပါဘူး။
စာတိုက်ကနေ ပါဆယ်ထုပ် လာယူတာနဲ့ တူပါတယ်။ ပထမဆုံး ကောင်တာက ပါဆယ်ထုပ်ကို ပေးပြီး ထုပ်ပိုးထားတဲ့ label (status နဲ့ headers) ကို ချက်ချင်း ဖတ်လို့ရပါတယ်။ အထဲက ပစ္စည်း (body) ကိုတော့ ထုပ်ဖွင့်မှ ရပါတယ်၊ အဲဒါက response.json() ဒါမှမဟုတ် response.text() ကို await လုပ်တာပါ။ Label မှာ 'ပို့လို့ မရပါ' လို့ ရေးထားနိုင်တဲ့အတွက် မဖွင့်ခင် label ကို အရင် ဖတ်ရပါမယ်။
Problem → Why → Solution
ပြဿနာ: error page ကို data လို့ ယူမိတယ်
အောက်က code က user မရှိတဲ့အခါ catch ထဲ ရောက်မယ်လို့ ထင်ရပါတယ်။ တကယ်တော့ server က 404 ပြန်ပေးရင် fetch က ကောင်းကောင်း fulfilled ဖြစ်ပြီး { error: "Not Found" } ကို user အဖြစ် ယူသွားပါတယ်။ user.name က undefined ဖြစ်ပြီး screen ပေါ်မှာ "Hello, undefined" ပေါ်လာပါတယ်။ Server က HTML error page ပြန်ပေးရင်တော့ json() က SyntaxError နဲ့ fail ဖြစ်ပြီး အမှန်တကယ်ဖြစ်တဲ့ ပြဿနာ (HTTP 500) ကို ဖုံးကွယ်သွားပါတယ်။
async function showUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json(); // also runs for 404 and 500
greet(`Hello, ${user.name}`); // "Hello, undefined"
} catch (error) {
showError(error); // only network failures and bad JSON get here
}
}fetch က ဘာကြောင့် reject မဖြစ်တာလဲ
fetch အတွက် 404 ဒါမှမဟုတ် 500 က 'အောင်မြင်စွာ ရလာတဲ့ response' ပါ၊ server က အဖြေတစ်ခု ပြန်ပေးခဲ့လို့ပါ။ Promise က network ချို့ယွင်းတာ၊ CORS ပိတ်တာ၊ abort လုပ်တာလို response တစ်ခုမှ မရတဲ့အခါမှ reject ဖြစ်ပါတယ်။ ဒါကြောင့် body ကို မဖတ်ခင် response.ok (status 200-299) ကို ကိုယ်တိုင် စစ်ရပါမယ်။
Core concept: request တစ်ခု၊ Promise နှစ်ဆင့်
fetch(url, options) က အဆင့်နှစ်ဆင့်နဲ့ အလုပ်လုပ်ပါတယ်။ ပထမ await က response headers ရောက်လာတာနဲ့ Response object ကို ပေးပါတယ်: response.status (ဥပမာ 200, 404)၊ response.ok (status 200-299 ဆိုရင် true)၊ response.headers.get("content-type")။ ဒီအချိန်မှာ body က download ဆွဲနေဆဲ ဖြစ်နိုင်ပါတယ်။ ဒုတိယ await ဖြစ်တဲ့ response.json() က body အားလုံး ရောက်တဲ့အထိ စောင့်ပြီး JSON အဖြစ် parse လုပ်ပါတယ်။
Body က stream တစ်ခုဖြစ်လို့ တစ်ကြိမ်ပဲ ဖတ်လို့ရပါတယ်။ json(), text(), blob(), arrayBuffer() ထဲက တစ်ခုကို ရွေးပါ၊ json() ပြီးမှ text() ထပ်ခေါ်ရင် TypeError ရပါတယ် (response.bodyUsed က true ဖြစ်သွားပြီ)။ Body ကို နှစ်ခါ လိုရင် response.clone() ကို မဖတ်ခင် ခေါ်ထားပါ။ json() ကလည်း body က JSON မမှန်ရင် SyntaxError နဲ့ reject ဖြစ်ပါတယ်။
Options object က request ကို ပုံဖော်ပါတယ်: method (default က GET)၊ headers၊ body၊ signal။ fetch က object ကို အလိုအလျောက် JSON မပြောင်းပေးပါဘူး၊ ဒါကြောင့် body: JSON.stringify(data) နဲ့ "Content-Type": "application/json" header ကို ကိုယ်တိုင် ထည့်ရပါတယ်။ fetch မှာ built-in timeout မပါပါဘူး၊ AbortController ကို ဖန်တီးပြီး signal ကို ပေးကာ အချိန်ကျော်ရင် controller.abort() ကို ခေါ်ရပါတယ်။ Abort ဖြစ်ရင် fetch က name "AbortError" ပါတဲ့ error နဲ့ reject ဖြစ်ပါတယ်။
| ဖြစ်ရပ် | fetch ရဲ့ အပြုအမူ | ဘယ်လို စစ်မလဲ |
|---|---|---|
| 200 OK + JSON | fulfilled | response.ok က true |
| 404 / 500 | fulfilled | response.ok က false၊ status ကို ကြည့် |
| Network ကျ / CORS ပိတ် | TypeError နဲ့ reject | catch block |
| Abort / timeout | AbortError နဲ့ reject | error.name ကို စစ် |
Browser မှာတော့ CORS နဲ့ credentials ကိုလည်း သတိထားရပါတယ်။ တခြား origin ဆီ request ပို့တဲ့အခါ server က Access-Control-Allow-Origin header နဲ့ ခွင့်ပြုမှ JavaScript က response ကို ဖတ်ခွင့်ရပါတယ်။ Cookie တွေကို cross-origin request နဲ့ ပို့ချင်ရင် credentials: "include" ကို ထည့်ရပါတယ်။
Parse ပြီးသား JSON ကိုလည်း မယုံပါနဲ့
response.json() အောင်မြင်တာက body က JSON syntax မှန်တယ်ဆိုတာကိုပဲ ပြောပါတယ်။ လိုအပ်တဲ့ field တွေ ပါမပါ၊ type မှန်မမှန်ကိုတော့ မစစ်ပါဘူး။ ကိုယ်မထိန်းချုပ်တဲ့ API ကလာတဲ့ data ကို မသုံးခင် shape ကို စစ်ပါ (JSON lesson မှာ ဆက်လေ့လာပါမယ်)။
- await fetch → Response (headers ပဲ)
- response.ok နဲ့ status ကို စစ်
- await response.json() → data
- Body ကို တစ်ကြိမ်ပဲ ဖတ်လို့ရ
fetch ရဲ့ catch က 'response မရခဲ့ဘူး' ကိုပဲ ဖမ်းပါတယ်၊ 'response က မကောင်းဘူး' ကိုတော့ response.ok နဲ့ ကိုယ်တိုင် စစ်ရပါတယ်။
အထွေထွေ ပုံစံ
const response = await fetch(url, {
method: "POST", // default is "GET"
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload), // GET requests have no body
signal: controller.signal, // optional: allows abort
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json(); // read the body onceRequest ကို options object နဲ့ ဖော်ပြပြီး fetch ကို await လုပ်ပါ။ Status ကို အရင် စစ်ပြီးမှ body ကို ဖတ်တဲ့ method တစ်ခုကို await လုပ်ပါ။
Worked example: status ကို စစ်တဲ့ getTodo
Lesson ထဲကနေ API အစစ်ကို ခေါ်ရင် output က network ပေါ် မူတည်သွားပြီး status ကို မစစ်တဲ့ code က 404 ကိုလည်း success လို သဘောထားပါတယ်။ ဒီမှာ getTodo က fetch function ကို parameter အဖြစ် လက်ခံပြီး response.ok ကို စစ်ပါတယ်: production မှာ default fetch ကို သုံးပြီး ဒီမှာတော့ တကယ့် Response object တွေ ပြန်ပေးတဲ့ fakeFetch ကို ပေးထားလို့ network မလိုဘဲ output က အမြဲ တူပါတယ်။ id 1 က todo ကို ပြပြီး id 999 က 404 error ကို ပြပါတယ်။
// A stand-in for the network. It returns real Response objects, so getTodo
// works unchanged with the real fetch in a browser or in Node 18+.
const todos = {
1: { userId: 1, id: 1, title: "delectus aut autem", completed: false },
};
async function fakeFetch(url) {
const id = Number(new URL(url).pathname.split("/").pop());
if (!todos[id]) {
return new Response(JSON.stringify({ error: "Not Found" }), { status: 404 });
}
return new Response(JSON.stringify(todos[id]), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
async function getTodo(id, fetchFn = fetch) {
const response = await fetchFn(`https://jsonplaceholder.typicode.com/todos/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} while loading todo ${id}`);
}
return response.json();
}
async function main() {
for (const id of [1, 999]) {
try {
const todo = await getTodo(id, fakeFetch);
console.log(todo);
} catch (error) {
console.log("Could not fetch data:", error.message);
}
}
}
main();Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Build a real Response
return new Response(JSON.stringify(todos[id]), {Response constructor က fetch ပြန်ပေးတဲ့ class အတိုင်းပါပဲ၊ body string, status နဲ့ headers ကို ပေးလိုက်ရင် ok, status, json() အားလုံး တကယ့် response လို အလုပ်လုပ်ပါတယ်။
- Inject fetch
async function getTodo(id, fetchFn = fetch) {fetchFn ကို မပေးရင် global fetch ကို သုံးပါတယ်။ Test နဲ့ ဒီ lesson မှာတော့ fakeFetch ကို ပေးလို့ network မလိုတော့ပါဘူး။
- Check before reading
if (!response.ok) {404 response အတွက် fetch က fulfilled ဖြစ်ပေမဲ့ ok က false ဖြစ်ပါတယ်။ ဒီနေရာမှာ ကိုယ်ပိုင် Error ကို throw လုပ်လိုက်လို့ caller ရဲ့ catch က ဖမ်းနိုင်ပါတယ်။
- Read the body
return response.json();Status ကောင်းမှသာ body ကို JSON အဖြစ် parse လုပ်ပါတယ်။ async function ထဲက return ဖြစ်လို့ caller က await နဲ့ parse ပြီးသား object ကို ရပါတယ်။
- Handle each case
console.log("Could not fetch data:", error.message);id 999 အတွက် getTodo က throw လုပ်ခဲ့တဲ့ message ကို ဒီမှာ ပြပါတယ်။ Loop ဆက်သွားလို့ id တစ်ခု fail ဖြစ်လည်း ကျန်တာကို ထိခိုက်မှု မရှိပါဘူး။
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }
Could not fetch data: HTTP 404 while loading todo 999POST နဲ့ data ပို့ခြင်း
Data ပို့တဲ့အခါ method, header နဲ့ string ဖြစ်အောင် ပြောင်းထားတဲ့ body သုံးခုလုံး လိုပါတယ်။ အောက်က echoServer က လက်ခံရရှိတာကို ပြန်ပြောပြပြီး Response.json() နဲ့ 201 Created ကို ပြန်ပေးပါတယ်။ Output မှာ method က POST၊ content type က application/json၊ body က object အဖြစ် ပြန်ရောက်လာကြောင်း မြင်ရပါတယ်။
// The fake server echoes what it received, so we can see what fetch sent.
async function echoServer(url, options = {}) {
const received = {
method: options.method ?? "GET",
contentType: new Headers(options.headers).get("content-type"),
body: JSON.parse(options.body),
};
return Response.json({ id: 101, ...received }, { status: 201 });
}
async function createPost(post, fetchFn = fetch) {
const response = await fetchFn("https://api.example.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(post), // fetch does not serialise objects for you
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return { status: response.status, data: await response.json() };
}
createPost({ title: "Hello", draft: true }, echoServer).then(console.log);လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ fetch
Project အများစုက fetch ကို component တိုင်းမှာ တိုက်ရိုက် မခေါ်ပါဘူး။ getJson လို helper function သေးသေးလေး တစ်ခု (ဒါမှမဟုတ် api client module တစ်ခု) ထဲမှာ status စစ်တာ၊ timeout၊ JSON parse လုပ်တာနဲ့ error message ပြောင်းတာတွေကို တစ်နေရာတည်းမှာ စုထားပါတယ်။ ဒါကြောင့် rule ပြောင်းရင် တစ်နေရာတည်းမှာ ပြင်ရုံပါပဲ။
- UI က loading, empty, error state သုံးမျိုးကို ပြရပါတယ်။ 404 က 'မတွေ့ပါ' ဖြစ်နိုင်ပြီး 500 က 'နောက်မှ ပြန်ကြိုးစားပါ'၊ timeout က 'connection နှေးနေပါတယ်' ဖြစ်နိုင်ပါတယ်။
- Search box မှာ user က စာရိုက်တိုင်း request အသစ် ပို့ရင် အရင် request ကို AbortController နဲ့ ဖျက်ပစ်ပါတယ်၊ ဒါမှ နှေးနှေး ရောက်လာတဲ့ အဟောင်းက အသစ်ကို ထပ်မရေးမိပါဘူး။
- fetch ကို parameter အဖြစ် inject လုပ်ထားလို့ unit test တွေက ဒီ lesson လိုပဲ Response object တွေနဲ့ 200, 404, 500, offline ဖြစ်ရပ်တွေကို network မလိုဘဲ စစ်နိုင်ပါတယ်။
အမှားများ
fetch နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
response.ok ကို မစစ်ခြင်း
fetch(...).then((r) => r.json()) က 404 နဲ့ 500 ကို အောင်မြင်တဲ့ data လို ကိုင်တွယ်ပါတယ်။ Error body ကို user data လို ပြမိတာ၊ HTML error page ကြောင့် မရှင်းလင်းတဲ့ SyntaxError ရတာတွေ ဖြစ်ပါတယ်။ Body ကို မဖတ်ခင် if (!response.ok) ကို အမြဲ စစ်ပါ။
Object ကို body အဖြစ် တိုက်ရိုက် ပေးခြင်း
body: { title: "Hi" } လို့ ရေးရင် fetch က object ကို string "[object Object]" အဖြစ် ပြောင်းပို့ပြီး server က parse မလုပ်နိုင်ပါဘူး။ JSON.stringify(data) ကို သုံးပြီး Content-Type header ကိုလည်း ထည့်ပါ။
Body ကို နှစ်ကြိမ် ဖတ်ခြင်း
Debug လုပ်ဖို့ console.log(await response.text()) ပြီးမှ response.json() ကို ခေါ်ရင် body ကို ဖတ်ပြီးသားဖြစ်ကြောင်း ပြောတဲ့ TypeError ရပါတယ်။ text() ကို တစ်ကြိမ်ဖတ်ပြီး JSON.parse ကို ကိုယ်တိုင် ခေါ်ပါ၊ ဒါမှမဟုတ် response.clone() ကို သုံးပါ။
fetch မှာ timeout ပါတယ်လို့ ယူဆခြင်း
fetch ကိုယ်တိုင်မှာ timeout option မရှိပါဘူး။ Server က connection ကို ဖွင့်ထားပြီး မဖြေရင် spinner က အကြာကြီး လည်နေနိုင်ပါတယ်။ Request တိုင်းကို AbortController (ဒါမှမဟုတ် AbortSignal.timeout(ms)) နဲ့ အချိန်ကန့်သတ်ပါ။
Best Practices
Best practices
- fetch ကို helper တစ်ခုထဲမှာ wrap လုပ်ပြီး status စစ်တာ၊ timeout နဲ့ error message ကို တစ်နေရာတည်းမှာ ထားပါ။
- Network error, HTTP error နဲ့ invalid data ကို message မတူအောင် ခွဲပြပါ၊ user က ဘာလုပ်ရမလဲ သိနိုင်ပါတယ်။
- Test လုပ်လို့ရအောင် fetch function ကို parameter အဖြစ် inject လုပ်ပြီး Response object တွေနဲ့ stub လုပ်ပါ။
Mini challenge
Mini challenge: timeout ပါတဲ့ getJson helper
Project တစ်ခုလုံးက သုံးနိုင်မယ့် getJson(url, { fetchFn, timeoutMs }) helper ကို ရေးပါ။ အတုလုပ်ထားတဲ့ network က အောင်မြင်တဲ့ JSON၊ 500၊ HTML login page၊ offline နဲ့ ဘယ်တော့မှ မဖြေတဲ့ slow server ဆိုတဲ့ ဖြစ်ရပ်ငါးမျိုးကို ပေးပါတယ်။ ဖြစ်ရပ်တစ်ခုချင်းစီအတွက် ရှင်းလင်းတဲ့ message တစ်ကြောင်း ထုတ်ရပါမယ်။
- AbortController နဲ့ setTimeout ကို သုံးပြီး timeoutMs ကျော်ရင် abort လုပ်ရမယ်၊ finally ထဲမှာ timer ကို clear လုပ်ရမယ်
- AbortError ကို "timed out after N ms" နဲ့ တခြား reject တွေကို "network error: ..." နဲ့ ပြောင်းရမယ်
- response.ok မဟုတ်ရင် "HTTP <status>" ကို throw လုပ်ရမယ်
- content-type မှာ application/json မပါရင် "expected JSON, got <type>" ကို throw လုပ်ရမယ်
// Fake network: each path simulates a different real-world situation.
function fakeNetwork(url, { signal } = {}) {
const path = new URL(url).pathname;
if (path === "/slow") {
// never answers by itself; only the abort signal can end the wait
return new Promise((_, reject) => {
signal?.addEventListener("abort", () => reject(signal.reason));
});
}
if (path === "/offline") return Promise.reject(new TypeError("fetch failed"));
if (path === "/broken") {
return Promise.resolve(new Response("Internal error", { status: 500 }));
}
if (path === "/login-page") {
const headers = { "Content-Type": "text/html" };
return Promise.resolve(new Response("<h1>Please log in</h1>", { headers }));
}
return Promise.resolve(Response.json({ path, ok: true }));
}
async function getJson(url, { fetchFn = fetch, timeoutMs = 5000 } = {}) {
// TODO: create an AbortController and a timer that aborts after timeoutMs
// TODO: await fetchFn(url, { signal }) inside try/catch/finally
// TODO: map AbortError and other errors to clear messages; clear the timer
// TODO: check response.ok, then the content-type, then return the JSON
}
// TODO: call getJson for /users, /broken, /login-page, /offline and /slow
// with fetchFn: fakeNetwork and timeoutMs: 50, printing "<path> -> <result>"ရလဒ်: /users -> { path: '/users', ok: true }၊ /broken -> HTTP 500၊ /login-page -> expected JSON, got text/html၊ /offline -> network error: fetch failed၊ /slow -> timed out after 50 ms ဆိုတဲ့ line ငါးကြောင်း ထွက်ရပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Abort လုပ်တဲ့အခါ reason မပေးရင် signal.reason က name "AbortError" ပါတဲ့ DOMException ဖြစ်ပါတယ်။ Header ကို ဖတ်ရင် response.headers.get("content-type") ?? "" လို့ ရေးပြီး header မရှိတဲ့ ဖြစ်ရပ်ကို ကာကွယ်ပါ။
အဖြေ ကြည့်ရန်
// Fake network: each path simulates a different real-world situation.
function fakeNetwork(url, { signal } = {}) {
const path = new URL(url).pathname;
if (path === "/slow") {
// never answers by itself; only the abort signal can end the wait
return new Promise((_, reject) => {
signal?.addEventListener("abort", () => reject(signal.reason));
});
}
if (path === "/offline") return Promise.reject(new TypeError("fetch failed"));
if (path === "/broken") {
return Promise.resolve(new Response("Internal error", { status: 500 }));
}
if (path === "/login-page") {
const headers = { "Content-Type": "text/html" };
return Promise.resolve(new Response("<h1>Please log in</h1>", { headers }));
}
return Promise.resolve(Response.json({ path, ok: true }));
}
async function getJson(url, { fetchFn = fetch, timeoutMs = 5000 } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
let response;
try {
response = await fetchFn(url, { signal: controller.signal });
} catch (error) {
if (error.name === "AbortError") throw new Error(`timed out after ${timeoutMs} ms`);
throw new Error(`network error: ${error.message}`);
} finally {
clearTimeout(timer);
}
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const type = response.headers.get("content-type") ?? "";
if (!type.includes("application/json")) throw new Error(`expected JSON, got ${type}`);
return response.json();
}
async function main() {
const paths = ["/users", "/broken", "/login-page", "/offline", "/slow"];
for (const path of paths) {
try {
const data = await getJson(`https://api.example.com${path}`, {
fetchFn: fakeNetwork,
timeoutMs: 50,
});
console.log(path, "->", data);
} catch (error) {
console.log(path, "->", error.message);
}
}
}
main();Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- fetch က headers ရောက်တာနဲ့ Response နဲ့ fulfilled ဖြစ်ပြီး 404/500 အတွက် reject မဖြစ်ပါဘူး၊ response.ok ကို ကိုယ်တိုင် စစ်ပါ။
- Body ကို json(), text() စတဲ့ method တစ်ခုနဲ့ တစ်ကြိမ်ပဲ ဖတ်လို့ရပါတယ်။
- POST အတွက် method, Content-Type header နဲ့ JSON.stringify လုပ်ထားတဲ့ body ကို ပေးပါ။
- Timeout နဲ့ cancel အတွက် AbortController ကို သုံးပြီး fetch ကို inject လုပ်ထားရင် network မလိုဘဲ test လုပ်နိုင်ပါတယ်။
MDN — Fetch API — MDN Web Docs