Frontend
Fetch API
Request JSON, handle HTTP failures and cancel stale requests.
Read responses
const response = await fetch('/api/items');Send a same-origin GET requestif (!response.ok) throw new Error(`HTTP ${response.status}`);Check HTTP status; 4xx/5xx do not automatically reject fetchconst data = await response.json();Parse a JSON body onceconst text = await response.text();Parse text instead of JSONRequest options
fetch('/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Ada' }) });Send JSONfetch('/api/items', { credentials: 'include' });Include credentials; cross-origin requests still need valid CORS policyfetch('/api/items', { cache: 'no-store' });Avoid the browser HTTP cache for this requestfetch('/api/items', { headers: { Accept: 'application/json' } });Request a JSON representationCancellation
const controller = new AbortController();Create a cancellation controllerfetch('/api/items', { signal: controller.signal });Connect a request to its signalcontroller.abort();Cancel an in-flight requestfetch('/api/items', { signal: AbortSignal.timeout(5000) });Abort after five seconds in supporting runtimes