Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Practice and Review

AJAX, JSON and Fetch Cheat Sheet

A compact cheat sheet for AJAX, JSON and fetch: request options, status codes, headers, JSON method rules, safe request patterns and the pitfalls that bite most often.

This page is meant to stay open in a second tab. It does not teach anything from scratch: every table links to the lesson that explains the idea in full. When you forget whether fetch() rejects on a 404 (it does not) or what JSON.stringify does with undefined, look here first.

The tables are grouped by the order in which a request travels: build the request, send it, read the response, handle trouble. Two small runnable examples at the end check the most surprising rules for you.

The request cycle in one picture

flowchart LR
  A["Your code<br/>fetch(url, options)"] --> B["Network"]
  B --> C["Server"]
  C --> D["Response<br/>status + headers + body"]
  D --> E{"response.ok?"}
  E -->|"yes"| F["Read body once<br/>json() / text() / blob()"]
  E -->|"no"| G["Throw your own error"]
  B -.->|"network failure"| H["Promise rejects<br/>TypeError"]

A promise rejects only when no response arrives at all; an HTTP error status is still a successful fetch.

For the full story, see your first fetch() request and handling errors in fetch.

fetch() options

fetch(resource, options) takes a URL string, a URL object or a Request as the first argument. Every option below is optional.

Option Common values What it does
method "GET" (default), "POST", "PUT", "PATCH", "DELETE" The HTTP verb. Write it in uppercase to be safe.
headers object, array of pairs, or Headers Request headers such as Content-Type, Accept, Authorization.
body string, FormData, URLSearchParams, Blob, ArrayBuffer, stream The payload. Not allowed with GET or HEAD.
signal AbortSignal Lets you cancel the request or give it a timeout.
credentials "same-origin" (default), "include", "omit" Whether cookies and HTTP auth are sent. Cross-origin cookies need "include" plus matching server headers.
mode "cors" (default), "same-origin", "no-cors" How cross-origin requests are treated. "no-cors" gives you an opaque response you cannot read.
cache "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached" How the request interacts with the browser's HTTP cache.
redirect "follow" (default), "manual", "error" What to do when the server answers with a 3xx redirect.
referrerPolicy "no-referrer", "strict-origin-when-cross-origin", ... How much of the current URL is sent in the Referer header.
keepalive true / false Lets a small request outlive the page, for example when a tab closes.
integrity "sha256-..." Subresource integrity check for the response body.
priority "high", "low", "auto" A hint about how important the request is.

More on the options in sending data and headers, auth and CORS.

Choosing the method

Method Purpose Has a body? Safe Idempotent
GET Read a resource No Yes Yes
POST Create something or trigger an action Yes No No
PUT Replace a resource completely Yes No Yes
PATCH Change part of a resource Yes No Not guaranteed
DELETE Remove a resource Rarely No Yes
HEAD Same as GET but headers only No Yes Yes
OPTIONS Ask what is allowed (CORS preflight uses it) No Yes Yes

"Safe" means the request should not change anything on the server. "Idempotent" means that sending it twice leaves the server in the same state as sending it once, which is what decides whether an automatic retry is acceptable. See HTTP for AJAX developers and retries and backoff.

Status codes you will meet

Code Name What to do in your code
200 OK Read the body.
201 Created Read the new resource; the Location header often holds its URL.
204 No Content Success with an empty body. Do not call response.json().
301 / 308 Moved permanently fetch follows it; update stored URLs.
302 / 303 / 307 Redirect fetch follows it; response.redirected becomes true.
304 Not Modified Your cached copy is still good (the browser handles this for you).
400 Bad Request The request is malformed; read the error body.
401 Unauthorized Not signed in, or the token expired. Sign in again.
403 Forbidden Signed in but not allowed. Retrying will not help.
404 Not Found The URL or the resource id is wrong.
409 Conflict State clash, such as a duplicate or an outdated version.
415 Unsupported Media Type Check your Content-Type header.
422 Unprocessable Content Validation failed; the body usually lists field errors.
429 Too Many Requests Slow down; honour Retry-After.
500 Internal Server Error A server bug. Retry only if the request is idempotent.
502 / 503 / 504 Gateway or overload problems Often temporary; retry with backoff.

Rule of thumb: 2xx worked, 3xx look elsewhere, 4xx your request is the problem, 5xx the server is the problem.

Headers worth knowing

Header Direction Meaning
Content-Type both The format of the body, such as application/json. Set it yourself for JSON; fetch sets it for FormData (with the boundary) and URLSearchParams.
Accept request The formats you are able to read.
Authorization request Credentials, usually Bearer <token>.
Cache-Control both Caching rules: no-store, max-age=60, no-cache.
ETag / If-None-Match response / request A version tag and the conditional request that uses it; the server can answer 304.
Retry-After response Seconds (or a date) to wait before trying again.
Location response Where a redirect or a newly created resource lives.
Set-Cookie / Cookie response / request Cookie exchange. Prefer HttpOnly; Secure; SameSite cookies for sessions.
Origin request Added by the browser on cross-origin requests; the server decides whether to allow it.
Access-Control-Allow-Origin response The CORS answer that lets your page read the response.
X-Request-Id (custom) both A correlation id that helps when you debug with the server team.

A request is sent without a preflight only when it uses GET, HEAD or POST, carries only simple headers, and has a form-like Content-Type. Sending application/json or an Authorization header triggers an OPTIONS preflight first. Details are in headers, auth and CORS and debugging network requests.

Reading the Response

Member Type Notes
response.ok boolean true for statuses 200 to 299.
response.status number The numeric code.
response.statusText string Often empty over HTTP/2, so never show it to users.
response.headers Headers Case-insensitive: headers.get("content-type").
response.url string The final URL after redirects.
response.redirected boolean true if at least one redirect happened.
response.json() promise Parses the body as JSON; rejects with SyntaxError on bad input.
response.text() promise The body as a string.
response.blob() promise Files and images.
response.arrayBuffer() promise Raw bytes.
response.formData() promise A multipart or form-encoded body.
response.body ReadableStream For reading in chunks.
response.clone() Response A second copy so two readers can each consume a body.

A body can be read exactly once. A second json() call on the same response rejects with a TypeError; clone first if you need both text and JSON. See the Response object.

JSON methods and rules

Task Code Watch out for
Text to value JSON.parse(text) Throws SyntaxError on invalid JSON. Wrap in try/catch.
Value to text JSON.stringify(value) Returns undefined (not a string) for a bare undefined or function.
Pretty print JSON.stringify(value, null, 2) The third argument is the indent: a number up to 10 or a string.
Pick keys JSON.stringify(value, ["id", "name"]) An array replacer is a whitelist of property names.
Transform output JSON.stringify(value, (key, val) => ...) A function replacer runs for every key.
Transform input JSON.parse(text, (key, val) => ...) A reviver is how you turn date strings back into Date objects.
Custom output toJSON() method on your object Date has one, which is why dates become ISO strings.

What JSON.stringify does with values that JSON cannot hold:

Value In an object In an array
undefined, function, symbol The property is omitted Becomes null
NaN, Infinity, -Infinity null null
Date ISO string (through toJSON) ISO string
Map, Set {} (data is lost) {}
BigInt Throws TypeError Throws TypeError
Circular reference Throws TypeError Throws TypeError

JSON syntax is stricter than a JavaScript object literal: double quotes only, no trailing commas, no comments, no undefined, and keys must be quoted. See JSON syntax, parse and stringify and revivers, replacers and toJSON.

Patterns that save you

Always check ok, then parse:

JavaScript
const response = await fetch(url);
if (!response.ok) {
  throw new Error("HTTP " + response.status);
}
const data = await response.json();

Send JSON:

JavaScript
await fetch("/api/notes", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ text: "Hello" }),
});

Run requests in parallel and tolerate failures:

JavaScript
const results = await Promise.allSettled([fetch(a), fetch(b)]);

Cancel or time out:

JavaScript
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });

Build a query string safely:

JavaScript
const params = new URLSearchParams({ q: "ajax & json", page: 2 });
const url = "/api/search?" + params;
Need Use Lesson
Several independent requests Promise.all or Promise.allSettled Async/await for requests
First answer wins Promise.any or Promise.race Async/await for requests
Ignore stale search results Abort the previous controller Cancelling requests
Temporary failures Retry with exponential backoff and jitter Retries and backoff
Fresh data without hammering the server Cache in memory, poll gently Caching and polling
Form submission without a reload preventDefault() plus FormData Submitting forms with AJAX
Live updates from the server SSE or WebSocket instead of polling Streaming and real-time APIs

Pitfalls checklist

Pitfall Symptom Fix
Assuming fetch rejects on 404 or 500 Error pages parsed as data Check response.ok and throw.
Forgetting await before response.json() You get a Promise instead of data await it, or return the promise chain.
Reading a body twice TypeError: body stream already read Read once, or clone() first.
Calling json() on a 204 SyntaxError: Unexpected end of JSON input Check the status or read text() first.
Missing Content-Type on a JSON POST Server sees an empty or form body Set application/json.
Putting secrets in front-end code Anyone can read your API key Call your own server, which holds the secret.
Inserting API text with innerHTML Cross-site scripting (XSS) Use textContent or escape the data.
Out-of-order responses Old search results replace new ones Abort the previous request.
Retrying a non-idempotent POST blindly Duplicate orders Use idempotency keys or do not retry.
Silent CORS failure TypeError: Failed to fetch in the console The server must send Access-Control-Allow-Origin; you cannot fix it from the client.

See AJAX security and rendering API data.

Try the surprising rules

This first example needs no server. It builds Response objects by hand and checks how ok, 204 and body reading behave.

JS Response rules in practice

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second example shows what JSON.stringify and JSON.parse do with values that JSON cannot represent, and how a reviver brings a date back.

JS JSON round trip surprises

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request returns HTTP 500. What does the promise from fetch() do?

    fetch rejects only when no response could be obtained, for example a network failure or a blocked CORS request. Any HTTP status, including 404 and 500, resolves normally, so you must check response.ok yourself.
  2. 2. What does JSON.stringify do with a property whose value is undefined inside an object?

    Properties holding undefined, functions or symbols are omitted from objects. Inside arrays the same values become null so that positions stay stable.
  3. 3. Why does a JSON POST with an Authorization header usually cause an extra OPTIONS request?

    A cross-origin request with a JSON Content-Type or an Authorization header is not 'simple', so the browser first asks the server with an OPTIONS preflight whether the real request is allowed.
  4. 4. Which request method is idempotent, and therefore the safest to retry automatically?

    PUT replaces a resource with the same content, so repeating it leaves the same state. POST can create duplicates, and PATCH is only idempotent if the server designs it to be.

Summary

  • fetch resolves for every HTTP status; check response.ok and throw your own error.
  • A response body can be read once; use clone() if you need two reads, and do not parse a 204.
  • Set Content-Type: application/json yourself when you send JSON, and use URLSearchParams for query strings.
  • JSON.stringify drops undefined and functions in objects, turns them into null in arrays, loses Map and Set contents, and throws on BigInt and circular data.
  • Retry only idempotent requests or temporary 429 and 5xx failures, with backoff, and cancel stale requests with AbortController.
  • Never put secrets in front-end code, and never insert API text with innerHTML.

You have reached the end of the track. To revisit the foundations, start again with What Is AJAX?.