Fetch is the browser’s Promise-based HTTP API. It does not throw on 404 or 500 — you check response.ok or status. Send JSON with Content-Type and JSON.stringify, or FormData for files. AbortController cancels in-flight requests when the user navigates away.
This JavaScript cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- GET:
fetch(url)— default method. Put params in the query string. - POST JSON:
method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(data). - Form:
body: new FormData(form)— do not set Content-Type; the browser sets the boundary. - ok:
res.okis status 200–299. Stillawait res.json()ortext()once. - Headers:
res.headers.get("content-type"). Request headers go on the init object. - CORS: Cross-origin reads need server
Access-Control-*.credentials: "include"for cookies. - Abort:
signalfromAbortController. CatchAbortErrorseparately. - Cache:
cache: "no-store"when you must bypass HTTP cache for dashboards.
Copy-paste examples
JSON GET and POST
Read the body once. Branch on status before assuming JSON.
async function api(path, { method = 'GET', json } = {}) {
const opts = { method, headers: { Accept: 'application/json' } };
if (json !== undefined) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(json);
}
const res = await fetch(path, opts);
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error((data && data.error) || 'HTTP ' + res.status);
return data;
}Common mistakes
- Forgetting
JSON.stringifyand sending[object Object]. - Setting
Content-Type: multipart/form-datamanually and breaking the boundary. - Calling
.json()twice on the same response. - Using fetch to another origin without CORS and blaming PHP for a “failed” request that never left the browser.
FAQ
- fetch vs XMLHttpRequest vs axios? Fetch is built-in. axios adds interceptors and older-browser behavior. XHR is legacy unless you need upload progress without extra code.
- Why is my cookie not sent? Cross-site needs
credentials: "include"and serverAccess-Control-Allow-Credentialsplus a specific origin, not*.
- How do I upload a file?
FormData.append("file", fileInput.files[0])and POST. PHP reads$_FILES.
Related JavaScript cheat sheets
- Javascript Cheat Sheet 2026
- Javascript Array Methods Cheat Sheet
- Javascript String Methods Cheat Sheet
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.