You will use the Fetch API to send HTTP requests, inspect responses, and parse JSON data with promises.
What it is
The Fetch API is the modern browser interface for making HTTP requests. Instead of callbacks, fetch() returns a Promise that resolves to a Response object once the network request completes. The request itself can be described with a URL and an options object, or with a Request object. Related terms include Headers, Request, Response, async/await, and the older XMLHttpRequest.
A useful mental model is: fetch sends a request and gives you a response envelope. The envelope contains status, headers, and a body stream. You must explicitly check whether the HTTP status is successful and explicitly choose how to read the body, such as response.json() or response.text().
Why it matters
- It provides a standard, promise-based way to talk to servers without loading a library.
- It works well with
async/await, making request code easier to read than nested callbacks. - It supports common HTTP methods, headers, request bodies, and response parsing.
- It integrates with browser features such as caching, CORS, and streaming responses.
- It is widely supported in modern browsers and many JavaScript runtimes.
Syntax or steps
The smallest useful pattern is:
const response = await fetch(url, options);
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
Here, url is the endpoint, and options can include method, headers, body, mode, and credentials. For a JSON POST request, set Content-Type to application/json and convert the JavaScript object with JSON.stringify().
Example
async function saveUser(data) {
const response = await fetch("/save", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
const result = await response.json();
return result;
}
saveUser({ name: "Ada", role: "admin" })
.then((result) => {
console.log("Saved:", result);
})
.catch((error) => {
console.error("Fetch failed:", error);
});
Part by part:
async function saveUser(data)lets the function useawaitinternally.fetch("/save", ...)sends a POST request to the local endpoint/save.headerstells the server the body is JSON.body: JSON.stringify(data)converts the JavaScript object into a JSON string.response.okis true only for HTTP status codes in the 200-299 range.response.json()reads the response body and parses it as JSON..catch()handles network failures or errors thrown by the code.
Common mistakes
- Assuming fetch rejects for 404 or 500. It usually resolves with a
Response. Fix: checkresponse.okorresponse.status. - Forgetting the JSON content type. Some servers reject the request. Fix: include
"Content-Type": "application/json"when sending JSON. - Reading the body twice. A response body can usually be consumed only once. Fix: store the parsed value in a variable.
- Ignoring network errors. DNS failures, offline requests, and CORS errors reject the promise. Fix: use
.catch()ortry/catch.
When to use it
Use Fetch when you need a built-in, standard HTTP client. Use XMLHttpRequest only when maintaining very old code or needing legacy upload progress events. Use a library such as Axios when you want extra conveniences like automatic JSON handling, request cancellation, or interceptors.
| Task | Best choice | Reason |
|---|---|---|
| Simple GET or POST in modern code | fetch() | Native, promise-based, no dependency. |
| Legacy browser support | XMLHttpRequest | Older environments may not support Fetch. |
| Advanced request lifecycle features | HTTP library | Libraries may add interceptors, cancellation, and retries. |
Practice
Guided exercise: Write a function called loadUsers() that sends a GET request to /api/users, checks response.ok, and returns the parsed JSON. Expected behavior: if the server returns [{"id":1,"name":"Ada"}], the function resolves to that array.
Challenge: Extend the function to send a POST request to /api/users with a new user object. Hint: use method: "POST", JSON headers, and JSON.stringify().
Quick check
Question: If a server returns status 404, does fetch() reject automatically?
Answer: No. It resolves with a Response whose ok property is false. You must check the status yourself.
Summary
The Fetch API is a promise-based HTTP client for modern JavaScript. It gives you a Response object, but you are responsible for checking success and parsing the body. Mastering fetch() gives you a portable foundation for browser and server-side network requests.