جلب البيانات (GET)
async function getUsers() {
const res = await fetch("https://api.example.com/users");
if (!res.ok) throw new Error(`خطأ ${res.status}`);
return res.json();
}
إرسال البيانات (POST)
async function createUser(data) {
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
return res.json();
}
مع مصادقة
fetch("/api/profile", {
headers: { Authorization: `Bearer ${token}` }
});
معالجة الأخطاء
try {
const users = await getUsers();
} catch (err) {
console.error("فشل الجلب:", err.message);
}
بديل: axios
import axios from "axios";
const { data } = await axios.get("/api/users"); // يحلّل JSON تلقائيًّا
🎯 التالي: CORS.