Fetch API
fetch is the built-in function for making HTTP requests from JavaScript: loading data from a server, sending a form, calling an API. It returns a promise that resolves to a Response object once the server replies; you then read the body as JSON, text or another format, which is a second asynchronous step. fetch works in every modern browser and in Node.js 18 and later. Its one big surprise is that an HTTP error such as 404 or 500 is not an error to fetch: you must check response.ok yourself.
In One Minute
const response = await fetch(url)makes a GET request;await response.json()reads a JSON body.- Check
response.ok(status 200 to 299).fetchonly rejects on network failures, not on 404 or 500. - POST JSON with
fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }). - A body can be read once:
json(),text(),blob(),formData()orarrayBuffer(). - Show fetched data with
textContentorcreateElement, never by inserting it as HTML.
This lesson uses await, which pauses an async function until a promise settles. The async chapter explains promises in depth; here it's enough to read await fetch(...) as "wait for the response". The examples load small JSON files that this page provides, shown first.
A GET Request
[
{ "id": 1, "name": "Navika", "amount": 120 },
{ "id": 2, "name": "Srihitha", "amount": 85 },
{ "id": 3, "name": "Advitha", "amount": 45 }
]Syntax
const response = await fetch(url, options);
const data = await response.json();Example
<ul id="list"></ul>
<script type="module">
const response = await fetch("/api/payments.json");
console.log(response.status, response.ok, response.headers.get("content-type"));
const payments = await response.json();
console.log(payments.length, "payments, total", payments.reduce((s, p) => s + p.amount, 0));
const list = document.querySelector("#list");
for (const p of payments) {
const li = document.createElement("li");
li.textContent = `${p.name}: $${p.amount}`;
list.append(li);
}
console.log(list.children.length, "rows shown");
</script>200 true application/json
3 payments, total 250
3 rows shownExplanation: the first await waits for the response headers: the status code and content type are available then. The second await waits for the body to download and be parsed as JSON. Module scripts (type="module") allow await at the top level; elsewhere, put the code in an async function.
The Response Object
| Property or method | Gives |
|---|---|
status | The HTTP status code, such as 200 or 404 |
ok | true for statuses 200 to 299 |
statusText | The status message (often empty with HTTP/2) |
headers.get(name) | A response header |
url | The final URL, after any redirects |
json() | A promise for the body parsed as JSON |
text() | A promise for the body as a string |
blob(), arrayBuffer(), formData() | The body as binary data or form data |
A body is a stream that can be read once. Calling response.json() and then response.text() fails with TypeError: body stream already read; use response.clone() if you truly need both.
Checking response.ok
fetch resolves successfully whenever the server answers, even with an error status. A 404 is still a response:
<script type="module">
const response = await fetch("/api/missing.json");
console.log("fetch resolved; status", response.status, "ok", response.ok);
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`Request to ${url} failed with HTTP ${res.status}`);
return res.json();
}
try {
await getJson("/api/missing.json");
} catch (err) {
console.log(err.message);
}
console.log((await getJson("/api/payments.json"))[0].name);
</script>fetch resolved; status 404 ok false
Request to /api/missing.json failed with HTTP 404
NavikaSending Data: POST and Other Methods
To send data, set the method, the body, and a Content-Type header that says what the body is:
const response = await fetch("/api/payments", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Advitha", amount: 45 }),
});
if (!response.ok) throw new Error(`Save failed: HTTP ${response.status}`);
const saved = await response.json();| Option | Meaning |
|---|---|
method | "GET" (default), "POST", "PUT", "PATCH", "DELETE" |
headers | An object or Headers instance |
body | A string (JSON), FormData, URLSearchParams, Blob... |
signal | An AbortSignal to cancel (next lesson) |
credentials | "same-origin" (default), "include" (send cookies cross-origin), "omit" |
cache | "default", "no-store", "reload"... |
The checker's fake server only serves files, so it can't save anything; this next example uses Request objects, which describe a request without sending it, to show exactly what fetch would send:
const request = new Request("https://www.example.com/api/payments", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Advitha", amount: 45 }),
});
console.log(request.method, request.url);
console.log(request.headers.get("content-type"));
console.log(await request.text());POST https://www.example.com/api/payments
application/json
{"name":"Advitha","amount":45}Sending Form Data
FormData can be sent directly; the browser sets the right Content-Type (with a boundary) automatically, so don't set it yourself:
form.addEventListener("submit", async (event) => {
event.preventDefault();
const response = await fetch("/api/payments", { method: "POST", body: new FormData(form) });
if (!response.ok) showError(`Couldn't save (HTTP ${response.status})`);
});Query Strings
Build query strings with URLSearchParams, never by joining strings:
const params = new URLSearchParams({ grade: "9", status: "unpaid", q: "Zoë & Co" });
const url = `/api/payments?${params}`;
console.log(url);/api/payments?grade=9&status=unpaid&q=Zo%C3%AB+%26+CoNetwork Errors
fetch rejects (throws, when awaited) only when no response arrives at all: no internet connection, a server that doesn't exist, a CORS block, or a canceled request:
<script type="module">
try {
await fetch("https://no-such-server.example/api/payments");
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>TypeError | Failed to fetchThe error is deliberately vague (always TypeError, with a message like "Failed to fetch" in Chrome), so attackers can't use it to probe networks. Handle both kinds of failure: network errors in catch, and HTTP errors by checking response.ok. The next lesson covers status codes, CORS and timeouts in detail.
In Practice
The Fee Tracker loads payments, shows a loading message, handles HTTP and network errors with friendly messages, and renders rows safely:
[
{ "name": "Navika", "balance": 0 },
{ "name": "Srihitha <b>", "balance": 85 }
]<p id="status"></p>
<ul id="students"></ul>
<script type="module">
const status = document.querySelector("#status");
const list = document.querySelector("#students");
async function loadStudents(url) {
status.textContent = "Loading...";
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const students = await res.json();
list.replaceChildren(...students.map((s) => {
const li = document.createElement("li");
li.textContent = `${s.name}: ${s.balance > 0 ? `$${s.balance} due` : "paid"}`;
return li;
}));
status.textContent = `${students.length} students`;
} catch (err) {
status.textContent = `Couldn't load students (${err.message}). Try again.`;
}
console.log(status.textContent);
}
await loadStudents("/api/students.json");
console.log(list.children[1].textContent, "| bold elements:", list.querySelectorAll("b").length);
await loadStudents("/api/oops.json");
</script>2 students
Srihitha <b>: $85 due | bold elements: 0
Couldn't load students (HTTP 404). Try again.The student name containing <b> is shown as text, and no bold element was created. The second call hit a missing file, and the reader sees a clear message instead of a broken page.
Common Mistakes
Not checking response.ok. A 404 or 500 page gets parsed as if it were data, usually failing later with a confusing error. Check first.
Forgetting the second await. response.json() returns a promise; const data = response.json() gives a promise, not data.
Setting Content-Type for FormData. The browser must add the boundary itself. Leave the header out.
Reading the body twice. body stream already read. Read once, or clone() first.
Interview Corner
Does fetch reject on HTTP 404 or 500?
No. The promise resolves with a Response whenever the server replies, whatever the status. It rejects only on network failure, CORS violations or abort. Check response.ok (status 200 to 299) and throw for error statuses yourself.
How do you send JSON with fetch?
fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }), then check response.ok and read the reply with await response.json().
Practice
Challenge: Write fetchTotal(url) that loads an array of payments and returns the total amount, throwing an error with the status code when the response isn't OK. Call it on /api/payments.json and a missing file.
Show solution
<script type="module">
async function fetchTotal(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const payments = await res.json();
return payments.reduce((sum, p) => sum + p.amount, 0);
}
console.log(await fetchTotal("/api/payments.json"));
await fetchTotal("/api/none.json").catch((err) => console.log(err.message));
</script>250
HTTP 404Key Takeaways
| Task | Code |
|---|---|
| GET JSON | const data = await (await fetch(url)).json() |
| Check status | if (!res.ok) throw new Error(...) |
| POST JSON | fetch(url, { method: "POST", headers: {...}, body: JSON.stringify(d) }) |
| POST a form | fetch(url, { method: "POST", body: new FormData(form) }) |
| Read text | await res.text() |
Was this tutorial helpful?