JS: Fetch API
تعلّم Fetch API في JS مع أمثلة عملية.
JS — Fetch API
مقدمة
Fetch يسمح لك بجلب بيانات من APIs (JSON/نص) باستخدام Promises.
ماذا ستتعلم؟
- fetch الأساسي
- قراءة JSON
- معالجة الأخطاء
- async/await
الصياغة
const res = await fetch(url);
مثال
async function load(){
try{
const res = await fetch("https://api.github.com/zen");
if(!res.ok) throw new Error("HTTP " + res.status);
const text = await res.text();
console.log(text);
}catch(err){
console.error(err);
}
}
load();
ملاحظات
- دائماً افحص res.ok.
- استخدم try/catch مع async/await.
جرّب بنفسك: افتح Playground: /ar/playground/html