JavaScript Fetch API & AJAX Cheat Sheet
Covers making GET and POST requests with the Fetch API, handling errors, timeouts, and JSON, and the legacy XMLHttpRequest API.
1 PageIntermediateMar 28, 2026
Basic GET Request
fetch() returns a Promise that resolves to a Response.
javascript
fetch("/api/users") .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.error("Network error:", err));// With async/awaitasync function getUsers() { const response = await fetch("/api/users"); if (!response.ok) { throw new Error(`HTTP error ${response.status}`); } return response.json();}
POST with a JSON Body
Set headers and stringify the payload.
javascript
async function createUser(user) { const response = await fetch("/api/users", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, }, body: JSON.stringify(user), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json();}createUser({ name: "Alice", email: "alice@example.com" });
Error Handling & Timeouts
fetch only rejects on network failure, not HTTP errors.
javascript
async function fetchWithTimeout(url, ms = 5000) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), ms); try { const response = await fetch(url, { signal: controller.signal }); if (!response.ok) { throw new Error(`Server responded ${response.status}`); } return await response.json(); } catch (err) { if (err.name === "AbortError") console.error("Request timed out"); else console.error("Fetch failed:", err.message); throw err; } finally { clearTimeout(timer); }}// Note: fetch() only rejects on network failure -- a 404/500 still resolves with ok: false
Legacy XMLHttpRequest
Still useful for upload progress events fetch lacks by default.
javascript
const xhr = new XMLHttpRequest();xhr.open("GET", "/api/users");xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { console.log(JSON.parse(xhr.responseText)); }};xhr.onerror = () => console.error("Request failed");xhr.send();// XHR still has native upload-progress events fetch lacks by default:xhr.upload.onprogress = (e) => console.log(e.loaded / e.total);
fetch() Options Reference
Common fields in the fetch init object.
- method- HTTP verb: 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'
- headers- Object or Headers instance for request headers
- body- Request payload: string, FormData, Blob, or URLSearchParams
- credentials- 'omit' | 'same-origin' | 'include' -- whether to send cookies cross-origin
- mode- 'cors' | 'no-cors' | 'same-origin' -- cross-origin request behavior
- signal- AbortSignal used with AbortController to cancel the request
- response.ok- true for status codes 200-299; fetch does NOT reject on HTTP error statuses
Pro Tip
fetch() only rejects its promise on a network-level failure (DNS, CORS, offline) -- a 404 or 500 response still resolves successfully, so always check response.ok explicitly instead of relying on .catch() alone.
Was this cheat sheet helpful?
Explore Topics
#JavaScriptFetchAPIAJAX#JavaScriptFetchAPIAJAXCheatSheet#Programming#Intermediate#BasicGETRequest#POSTWithAJSONBody#ErrorHandlingTimeouts#LegacyXMLHttpRequest#APIs#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance