Fetch API
Makes HTTP requests without page reload. Returns a Promise.
async/await
Cleaner syntax for handling promises. Always wrap in try/catch.
Makes HTTP requests without page reload. Returns a Promise.
Cleaner syntax for handling promises. Always wrap in try/catch.
async function getData(url){
try{
const res=await fetch(url);
if(!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
}catch(e){
console.error(e.message);
}
}
// POST
fetch('/api/data',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({key:'value'})
});
More in JavaScript