SyntaxStudy
Sign Up
JavaScript Beginner 1 min read

Fetch API

Fetch API

Makes HTTP requests without page reload. Returns a Promise.

async/await

Cleaner syntax for handling promises. Always wrap in try/catch.

Example
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'})
});