fetch(), JavaScript'te bir sunucudan (API'den) veri çekmenin modern yoludur. Genellikle JSON verisi alıp sayfada göstermek için kullanılır.
1) then ile temel kullanım
fetch('https://api.ornek.com/veri')
.then(cevap => cevap.json())
.then(veri => console.log(veri))
.catch(hata => console.error('Hata:', hata));
2) async/await ile (daha okunur)
async function veriGetir() {
try {
const cevap = await fetch('https://api.ornek.com/veri');
if (!cevap.ok) throw new Error('HTTP ' + cevap.status);
const veri = await cevap.json();
console.log(veri);
} catch (hata) {
console.error('Hata:', hata);
}
}
veriGetir();
3) POST ile veri gönderme
await fetch('https://api.ornek.com/kayit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ad: 'Kuzey', puan: 100 })
});
Not: cevap.ok kontrolü önemlidir; fetch yalnızca ağ hatasında catch'e düşer, 404 gibi durumlarda düşmez. Bunu editörde JavaScript seçip deneyebilirsin.