The Code Fix

🔌 شرح REST APIs

استهلاك API من الكود

fetch — جلب البيانات (GET)

async function getUsers() {
  const response = await fetch("https://api.example.com/users");
  const data = await response.json();
  console.log(data);
}

إرسال بيانات (POST)

async function createUser() {
  const response = await fetch("https://api.example.com/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "براء", age: 25 }),
  });
  const result = await response.json();
  console.log(result);
}

معالجة الأخطاء

async function getUsers() {
  try {
    const res = await fetch("https://api.example.com/users");
    if (!res.ok) {
      throw new Error(`خطأ: ${res.status}`);
    }
    const data = await res.json();
    return data;
  } catch (error) {
    console.error("فشل الطلب:", error);
  }
}

💡 تحقّق دائمًا من res.okfetch لا يرمي خطأ تلقائيًا عند 404 أو 500.

الترويسات والمصادقة

fetch("https://api.example.com/profile", {
  headers: {
    "Authorization": "Bearer YOUR_TOKEN",
  },
});

أكواد الاستجابة المهمّة

الكودالمعنى
200نجاح
201تمّ الإنشاء
400طلب خاطئ
401غير مصرّح
404غير موجود
500خطأ في الخادم

🎯 التالي: بناء API وأفضل الممارسات.