JavaScript: Başlangıçtan İleri Seviyeye
Bölüm 19 / 312 dk okuma

Fetch API ile HTTP

GET, POST ve diğer HTTP isteklerini modern Fetch API ile yapma.

fetch modern tarayıcıların ve Node.js'in (18+) yerleşik HTTP istemcisidir.

GET

const res = await fetch("https://api.example.com/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();

fetch bir Response objesi döner. Body'yi okumak için bir metot çağırman gerekir: .json(), .text(), .blob(), .formData(), .arrayBuffer().

Response objesi

res.ok            // 200-299 ise true
res.status        // 200, 404, 500...
res.statusText    // "OK", "Not Found"
res.headers.get("content-type");
res.url

POST + JSON

const res = await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Furkan", role: "dev" }),
});
 
const created = await res.json();

Diğer methodlar

fetch(url, { method: "PUT", body: ... });
fetch(url, { method: "DELETE" });
fetch(url, { method: "PATCH", body: ... });

Form gönderme

const form = document.querySelector("form");
const data = new FormData(form);
 
await fetch("/api/upload", {
  method: "POST",
  body: data,  // multipart/form-data otomatik
});

URL parametreleri

const params = new URLSearchParams({
  q: "javascript",
  page: "2",
  sort: "date",
});
 
const res = await fetch(`/api/search?${params}`);
// /api/search?q=javascript&page=2&sort=date

Headers

fetch("/api/me", {
  headers: {
    Authorization: `Bearer ${token}`,
    "X-Custom": "değer",
  },
});

İstek iptal etme

const ctrl = new AbortController();
 
fetch("/api/slow", { signal: ctrl.signal })
  .then((r) => r.json())
  .catch((err) => {
    if (err.name === "AbortError") console.log("İptal edildi");
  });
 
// 3 saniye sonra iptal
setTimeout(() => ctrl.abort(), 3000);

React'te component unmount olduğunda devam eden isteği iptal etmek için şart.

Timeout pattern'i

async function fetchWithTimeout(url, ms = 5000) {
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), ms);
  try {
    return await fetch(url, { signal: ctrl.signal });
  } finally {
    clearTimeout(timer);
  }
}

Modern Node.js / browserlerde ayrıca AbortSignal.timeout(5000) kısayolu da var.

CORS, credentials, mode

fetch("/api", {
  mode: "cors",                  // varsayılan
  credentials: "include",         // cookieleri gönder
  cache: "no-store",
});

Hata yönetimi şablonu

async function api(path, options = {}) {
  const res = await fetch(path, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...options.headers,
    },
  });
 
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`HTTP ${res.status}: ${text}`);
  }
 
  return res.status === 204 ? null : res.json();
}
 
const user = await api("/api/users/1");
const created = await api("/api/users", {
  method: "POST",
  body: JSON.stringify({ name: "F" }),
});

Projende sık kullanacağın bir wrapper.

Bu bölümü bitirdin mi?

İlerlemen tarayıcıda saklanır, eğitim listesinde görünür.

Paylaş