fetch JSON: GET, POST, Headers, and Errors
Lesson 15 of 38 in the JavaScript learning path.
How do I GET and POST JSON with fetch and handle HTTP errors?
fetch starts an HTTP request and returns a promise of a Response. The promise fulfills for HTTP error statuses too, so response.ok is the check that separates a 200 from a 404. Reading the body with text first gives you one string you can show in an error and, when the status is OK, pass to JSON.parse. An empty body becomes null instead of a parse error. GET sends Accept so the server knows you want JSON. POST also sets Content-Type and sends JSON.stringify of a progress object.
AbortSignal.timeout stops a call that never finishes. The sample posts to https://example.com/api/lessons and can GET a relative /api/lessons path. Neither call puts a password or token in the body. The page can describe the Request, including method, URL, headers, and body, without sending it. A renderer then draws a lesson list from JSON. A live call still needs the server to allow the browser origin.
Syntax & Parameters
const response = await fetch(url, { method, headers, body, signal });
if (!response.ok) throw new Error(String(response.status));
const data = JSON.parse(await response.text());
Example
Interactive preview available'use strict';
const progressPayload = { lessonSlug: 'js-fetch-json', percent: 40 };
function buildProgressRequest(payload) {
return new Request('https://example.com/api/lessons', {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}
async function describeRequest(request) {
const copy = request.clone();
const body = await copy.text();
return [`${copy.method} ${copy.url}`, `accept: ${copy.headers.get('accept')}`, `content-type: ${copy.headers.get('content-type')}`, body].join('\n');
}
async function readJson(response) {
const raw = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${raw.slice(0, 180)}`);
return raw.trim() === '' ? null : JSON.parse(raw);
}
async function getLessons(signal) {
const response = await fetch('/api/lessons', {
method: 'GET',
headers: { Accept: 'application/json' },
signal,
});
return readJson(response);
}
async function postProgress(payload, signal) {
return readJson(await fetch(buildProgressRequest(payload), { signal }));
}
function renderLessons(data, list) {
list.replaceChildren();
for (const lesson of data.lessons) {
const item = document.createElement('li');
item.textContent = `${lesson.title} (${lesson.minutes} min)`;
list.append(item);
}
}
const sample = { lessons: [{ title: 'Scope', minutes: 8 }, { title: 'fetch JSON', minutes: 9 }] };
async function showRequest() {
const text = await describeRequest(buildProgressRequest(progressPayload));
const log = document.getElementById('request-log');
if (log !== null) log.textContent = text;
console.log(text);
}
async function sendProgress() {
try {
console.log(JSON.stringify(await postProgress(progressPayload, AbortSignal.timeout(8000))));
} catch (error) {
console.log(error instanceof Error ? error.message : 'Request failed');
}
}
async function loadLessons() {
try {
console.log(JSON.stringify(await getLessons(AbortSignal.timeout(8000))));
} catch (error) {
console.log(error instanceof Error ? error.message : 'Request failed');
}
}
const list = document.getElementById('lesson-list');
if (list !== null) renderLessons(sample, list);
const buildButton = document.getElementById('build-request');
if (buildButton !== null) buildButton.addEventListener('click', () => { showRequest(); });
const sendButton = document.getElementById('send-progress');
if (sendButton !== null) sendButton.addEventListener('click', () => { sendProgress(); });
const loadButton = document.getElementById('load-lessons');
if (loadButton !== null) loadButton.addEventListener('click', () => { loadLessons(); });
showRequest();
Expected Output
#request-log and console:
POST https://example.com/api/lessons
accept: application/json
content-type: application/json
{"lessonSlug":"js-fetch-json","percent":40}
#lesson-list from the sample JSON:
Scope (8 min)
fetch JSON (9 min)
When the server answers 404 with {"message":"Lesson not found"}:
HTTP 404: {"message":"Lesson not found"}
Line-by-Line Walkthrough
- progressPayload is the JSON body: a lesson slug and a percent. It contains no password, token, or other secret.
- buildProgressRequest creates a POST Request to https://example.com/api/lessons with Accept, Content-Type, and a stringified body.
- describeRequest clones that Request, reads the clone body as text, and returns the method, URL, header values, and body.
- readJson reads the response as text first. A status that is not ok throws an Error that includes the status and a short slice of the body.
- An empty OK body becomes null. Any other OK body is parsed with JSON.parse, so invalid JSON rejects into the caller catch.
- getLessons sends GET /api/lessons with Accept set to application/json and passes the AbortSignal through.
- postProgress fetches the Request from buildProgressRequest and uses the same readJson path, so a 404 and a 201 share one error check.
- renderLessons clears the list and appends one text node per lesson title and minute count.
- showRequest prints the POST description without requiring the network to succeed. sendProgress performs the live POST with an eight-second timeout.
- On load the sample JSON is rendered and the request description is printed. The load button calls getLessons and the send button calls postProgress.
Common Pitfalls & Security
fetch does not reject on a 404 or a 500. Without response.ok you will parse an error page and treat it as data. Reading json() directly also throws away the raw text you needed for the error message, and it fails on an empty body. A live call to another origin needs that server to send CORS headers. The body is visible to the user and to logs, so it must not contain a password, a session cookie, or an access token. AbortSignal.timeout rejects with a TimeoutError or AbortError when the clock wins.
- Skipping response.ok treats an error payload as a successful lesson list.
- response.json() consumes the body. Read text once, then parse, or you cannot show the raw error.
- Sending credentials or tokens in JSON from a course page leaks them into history, logs, and the server you did not mean to call.
- result.innerHTML = raw parses the response. A message equal to the untrusted string <img src="x" alt="untrusted"> is an XSS hole. Render with textContent.
- A relative /api/lessons URL hits your own origin. example.com is a different origin and will fail the browser check until that host allows it.
Best Practices & Modern Standards
Set Accept on every JSON call and Content-Type when you send a body. Check response.ok before you parse, and keep the parser in one function so GET and POST share the timeout and the error shape. Pass AbortSignal.timeout so a hung socket cannot leave the button spinning. ES2024 does not change the rule that the server must validate again. The browser is only the caller.
Build the Request in a function you can describe in the UI before you send it. Render the success path from a plain object so the list code is testable without a network. Do not store the response in innerHTML. When you move from the sample to production, keep the same field names and let the server reject a percent outside 0 to 100.
Real-World Use
A course dashboard saves how far a student got in a lesson. The Save control builds the same POST the preview prints: URL, Accept, Content-Type, and a body with the slug and percent. The live button sends it with an eight-second timeout. A 201 updates the status from the JSON. A 404 shows the HTTP line from readJson.
The lesson list beside it can load from GET /api/lessons when the API is up. Until then, the page renders the sample JSON through the same function, so the layout is visible offline. The body never includes a token. The session cookie, if the site uses one, stays on the request the browser already manages for the same origin.
Frequently Asked Questions
Why does fetch succeed when the server returns 404?
The promise rejects when the network fails, not when the status is an error. response.ok is false for 404 and 500. Check it before you parse, and throw an error that includes the status and the response text.
Why read text before JSON?
You can only read the body once. text() gives you a string for the error message and for JSON.parse when the call worked. An empty string can become null instead of a parse exception on a 204 response.
What headers should a JSON POST send?
Send Accept: application/json so the server can return JSON, and Content-Type: application/json so it knows the body is JSON. Put the body through JSON.stringify. Do not put secrets in that object.
Why might the live call fail in the browser?
A request to example.com from your page is cross-origin. The browser blocks the response unless that host sends CORS headers that allow your origin. A same-origin path such as /api/lessons avoids that check and still needs the route to exist.