Almost every modern web app talks to a server. When you open a food delivery app, it loads restaurants from a server. When you post a comment, the comment is sent to a server. When you search for a product, the results come from a server.
In JavaScript, the standard way to make these network requests is the Fetch API. We've already had quick previews of fetch() in the Browser APIs and JSON chapters. Now that you understand promises and async/await, we can learn it properly.
Here's what a typical request looks like:
async function getUser() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log(user.name);
}
getUser();Output:
Leanne GrahamThe examples in this chapter use JSONPlaceholder (
jsonplaceholder.typicode.com), a free fake REST API for practice. You can run them in the browser console or in Node.js 18 or later, wherefetch()is also built in.
What is the Fetch API?
The Fetch API is a built-in JavaScript interface for making HTTP requests. The
fetch()function sends a request and returns a promise that resolves to aResponseobject.
Before fetch(), developers used an older API called XMLHttpRequest (XHR), which was callback-based and clumsy. fetch() is promise-based, so it works naturally with .then() and await.
A Quick HTTP Refresher
Every network request has two halves:
Your code ──── Request ────► Server
(method, URL, headers, body)
Your code ◄─── Response ──── Server
(status code, headers, body)HTTP Methods
Method | Used to | Example |
|---|---|---|
| Read data (the default) | Get a list of products |
| Create new data | Register a new user |
| Replace existing data completely | Replace a whole profile |
| Update part of existing data | Change only the phone number |
| Remove data | Delete a comment |
Status Codes
Range | Meaning | Common examples |
|---|---|---|
| Success |
|
| Redirect |
|
| Client error (problem with the request) |
|
| Server error |
|
Making a GET Request, Step by Step
Getting JSON data with fetch() is a two-step process:
async function getUser() {
// Step 1: send the request and wait for the response headers
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
// Step 2: read the body and parse it as JSON
const user = await response.json();
console.log(user.name);
console.log(user.email);
console.log(user.address.city);
}
getUser();Output:
Leanne Graham
Sincere@april.biz
GwenboroughWhy two awaits?
fetch()resolves as soon as the server sends back the status and headers. The body may still be downloading.response.json()reads the rest of the body and parses it as JSON. That also takes time, so it returns another promise.
The same thing with .then() looks like this:
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(user => console.log(user.name))
.catch(error => console.log("Error:", error.message));Output:
Leanne GrahamThe Response Object
The Response object tells you what the server sent back:
Property | Meaning |
|---|---|
|
|
| The status code, e.g. |
| The status message, e.g. |
| A |
| The final URL (after any redirects) |
And methods to read the body, each returning a promise:
Method | Returns |
|---|---|
| The body parsed as JSON |
| The body as a string |
| Binary data (for images, files) |
| The body as |
| Raw binary data |
async function inspect() {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
console.log(response.ok);
console.log(response.status);
console.log(response.headers.get("content-type"));
}
inspect();Output:
true
200
application/json; charset=utf-8The body can only be read once. After calling
response.json(), callingresponse.json()orresponse.text()again throws aTypeError(the body has already been used). If you need it twice, store the result in a variable, or callresponse.clone()before reading.
The Biggest Gotcha: fetch() Doesn't Reject on HTTP Errors
This surprises almost everyone. Try to fetch a user that doesn't exist:
async function getMissingUser() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/9999");
console.log("No error thrown!");
console.log(response.status, response.ok);
} catch (error) {
console.log("Caught:", error.message);
}
}
getMissingUser();Output:
No error thrown!
404 falseThe server answered with 404 Not Found, but the catch block didn't run.
The promise returned by
fetch()only rejects when the request couldn't be completed at all (no internet, DNS failure, blocked by CORS, or aborted). A 404 or 500 is still a valid response from the server, so the promise fulfills.
Situation | What |
|---|---|
200 OK | Fulfills, |
404 Not Found, 500 Server Error | Fulfills, |
No network, DNS failure, CORS blocked | Rejects with a |
Request aborted or timed out | Rejects with an |
So you must check response.ok yourself, and usually throw an error if it's false.
A Reusable, Safe Fetch Helper
In real projects, you'll often write a small helper so you don't repeat the checks everywhere:
async function getJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
async function main() {
try {
const user = await getJSON("https://jsonplaceholder.typicode.com/users/2");
console.log("Found:", user.name);
const missing = await getJSON("https://jsonplaceholder.typicode.com/users/9999");
console.log("Found:", missing.name); // never reached
} catch (error) {
console.log("Error:", error.message);
}
}
main();Output:
Found: Ervin Howell
Error: Request failed with status 404Now HTTP errors and network errors both end up in the same catch block.
Sending Data with POST
To send data, pass a second argument to fetch(): an options object. As we saw in the JSON chapter, objects must be converted to JSON text with JSON.stringify():
async function createPost() {
const newPost = {
title: "Learning Fetch",
body: "fetch() makes HTTP requests easy.",
userId: 1
};
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newPost)
});
const created = await response.json();
console.log(response.status);
console.log(created.id);
console.log(created.title);
}
createPost();Output:
201
101
Learning FetchThe server responded with 201 Created and returned the new post with an id. (JSONPlaceholder only pretends to save it, so it always returns id: 101.)
The most common options are:
Option | Purpose |
|---|---|
|
|
| Extra information, like |
| The data to send (a string, |
| An |
| Whether to send cookies: |
PATCH, PUT, and DELETE
These work the same way; only the method changes:
async function updateAndDelete() {
const patchResponse = await fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Updated title" })
});
const updated = await patchResponse.json();
console.log(patchResponse.status, updated.title);
const deleteResponse = await fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE"
});
console.log(deleteResponse.status, deleteResponse.ok);
}
updateAndDelete();Output:
200 Updated title
200 trueQuery Parameters
Many APIs accept filters in the URL, after a ?, like /posts?userId=1&_limit=3. Instead of gluing strings together by hand, use the built-in URL and URLSearchParams classes, which handle special characters (spaces, &, etc.) correctly:
async function getPosts() {
const url = new URL("https://jsonplaceholder.typicode.com/posts");
url.searchParams.set("userId", 1);
url.searchParams.set("_limit", 3);
console.log(url.toString());
const response = await fetch(url);
const posts = await response.json();
console.log(posts.length);
console.log(posts.map(p => p.id));
}
getPosts();Output:
https://jsonplaceholder.typicode.com/posts?userId=1&_limit=3
3
[ 1, 2, 3 ]const params = new URLSearchParams({ q: "laptop bag", page: 2 });
console.log(params.toString());Output:
q=laptop+bag&page=2Headers and Authentication
Protected APIs usually expect a token in the Authorization header:
const token = localStorage.getItem("authToken");
const response = await fetch("/api/profile", {
headers: {
"Authorization": `Bearer ${token}`,
"Accept": "application/json"
}
});(This is browser code: localStorage was covered in the storage chapter, and it runs inside an async function or module.)
Sending Form Data
To submit a form (including file uploads), you can send a FormData object directly. new FormData(form) is a built-in browser object that collects every named field of a <form> (including selected files) as key-value pairs:
const form = document.querySelector("#signup-form");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const response = await fetch("/api/signup", {
method: "POST",
body: new FormData(form) // don't set Content-Type yourself here
});
console.log(response.ok ? "Signed up!" : "Signup failed");
});When the body is
FormData, don't set theContent-Typeheader manually. The browser sets it tomultipart/form-datawith the correct boundary automatically.
Timeouts and Cancelling Requests
fetch() has no timeout by default. A slow server could keep your app waiting for a very long time. We control this with an AbortSignal.
Timeout with AbortSignal.timeout()
async function loadWithTimeout() {
try {
// httpbin's /delay/5 endpoint waits 5 seconds before responding
const response = await fetch("https://httpbin.org/delay/5", {
signal: AbortSignal.timeout(1000) // give up after 1 second
});
console.log(response.status);
} catch (error) {
console.log(error.name);
}
}
loadWithTimeout();Output:
TimeoutErrorCancelling with AbortController
Sometimes the user should be able to cancel, for example by clicking a "Cancel" button, or when they type a new search before the old one finishes. Use an AbortController:
const controller = new AbortController();
async function search() {
try {
const response = await fetch("https://httpbin.org/delay/5", {
signal: controller.signal
});
console.log(response.status);
} catch (error) {
if (error.name === "AbortError") {
console.log("Request was cancelled");
} else {
console.log("Error:", error.message);
}
}
}
search();
// Cancel after 200 ms (in a real app: when the user clicks "Cancel")
setTimeout(() => controller.abort(), 200);Output:
Request was cancelledHow it was stopped |
|
|---|---|
|
|
|
|
Multiple Requests in Parallel
Exactly as in the async/await chapter, independent requests should run together using Promise.all():
async function getJSON(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
async function loadDashboard() {
const base = "https://jsonplaceholder.typicode.com";
const [user, posts, todos] = await Promise.all([
getJSON(`${base}/users/1`),
getJSON(`${base}/posts?userId=1`),
getJSON(`${base}/todos?userId=1`)
]);
console.log(user.name);
console.log("Posts:", posts.length);
console.log("Todos:", todos.length);
}
loadDashboard();Output:
Leanne Graham
Posts: 10
Todos: 20If any request fails, Promise.all() rejects. Use Promise.allSettled() if you want to show whatever loaded successfully.
A Practical Example: Showing Data on a Page
Let's combine fetch with DOM manipulation. A good UI handles three states: loading, success, and error.
<button id="load-btn">Load Users</button>
<p id="status"></p>
<ul id="user-list"></ul>const button = document.querySelector("#load-btn");
const statusText = document.querySelector("#status");
const list = document.querySelector("#user-list");
button.addEventListener("click", async () => {
statusText.textContent = "Loading...";
button.disabled = true;
list.innerHTML = "";
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const users = await response.json();
for (const user of users) {
const li = document.createElement("li");
li.textContent = `${user.name} (${user.email})`;
list.appendChild(li);
}
statusText.textContent = `Loaded ${users.length} users`;
} catch (error) {
statusText.textContent = `Could not load users: ${error.message}`;
} finally {
button.disabled = false;
}
});Clicking the button shows "Loading...", then fills the list with 10 users and shows "Loaded 10 users". If the network fails, a friendly error message appears instead. Notice we used textContent, not innerHTML, to insert data from the server, which protects against injecting unwanted HTML.
CORS in One Minute
If you fetch from a different origin (a different domain, port, or protocol than your page), the browser applies a security rule called CORS (Cross-Origin Resource Sharing). The server must explicitly allow your origin by sending headers like Access-Control-Allow-Origin. If it doesn't, the browser blocks your code from reading the response, and fetch() rejects with a TypeError.
CORS is enforced by the browser, not by
fetch()itself. The same request from Node.js has no CORS restriction.You can't fix a CORS error from frontend code alone. The server needs to send the right headers (or you call the API through your own backend).
fetch() vs Alternatives
Feature |
|
| Axios (library) |
|---|---|---|---|
Built in | Yes (browsers, Node.js 18+) | Yes (browsers only) | No, install it |
Style | Promises | Events/callbacks | Promises |
Rejects on 4xx/5xx | No, check | No | Yes |
JSON parsing | Manual: | Manual | Automatic |
Timeout / cancel |
|
|
|
For most projects, plain fetch() plus a small helper like getJSON() is all you need.
Common Mistakes
Forgetting the second
await:const data = response.json();gives you a promise, not the data. Writeawait response.json().Not checking
response.ok: a 404 or 500 doesn't throw. Your code would then try to use an error page as data.Forgetting
JSON.stringify(): passing an object directly asbodysends the useless string"[object Object]".Forgetting the
Content-Typeheader when sending JSON, so the server doesn't know how to read the body.Reading the body twice: the body is a stream and can only be consumed once.
Calling
response.json()on an empty response (for example,204 No Content), which throws aSyntaxError. Check the status first.Running independent requests one after another instead of with
Promise.all().
Interview Tips
"Does
fetch()reject on a 404?" No. It only rejects on network failures, CORS blocks, and aborts. Checkresponse.okorresponse.status."Why does getting JSON need two
awaits?"fetch()resolves when headers arrive;response.json()reads and parses the body, which is a separate async step."How do you cancel or time out a request?" Pass a
signalfrom anAbortControllerorAbortSignal.timeout(ms)."What is CORS?" A browser security rule; the server must allow cross-origin requests with
Access-Control-Allow-*headers."PUT vs PATCH?" PUT replaces the whole resource; PATCH updates only the fields you send.
Practice ideas:
Build a search box that fetches results as the user types, cancelling the previous request with
AbortController.Write
fetchWithRetry(url, attempts)that retries on network errors or 5xx responses.Build a small "To-Do" page that loads, adds (POST), and deletes (DELETE) items using JSONPlaceholder.
Conclusion
The Fetch API is how JavaScript talks to servers. The essential pattern is:
async function getJSON(url) {
const response = await fetch(url); // 1. send request, get Response
if (!response.ok) { // 2. check the HTTP status
throw new Error(`HTTP ${response.status}`);
}
return response.json(); // 3. read and parse the body
}And for sending data:
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});Remember the key rules:
fetch() rejects only on network errors, CORS blocks, and aborts
404 / 500 → still fulfills, so check response.ok
Body → read once with json(), text(), blob()...
Timeouts → AbortSignal.timeout(ms) or AbortController
Parallel → await Promise.all([...])With promises, async/await, JSON, and fetch(), you now have everything you need to build pages that load and send real data.