Lesson 89 of 296
fetch and JSON APIs
What you will learn
- Making GET and POST requests with
fetch - Reading responses and checking for errors
- Sending JSON, form data and files
- Query strings with URLSearchParams
- Cancelling requests and timeouts
- Cookies and credentials
- CORS in one page
- Avoiding race conditions in search boxes
On this page
- What fetch is
- A GET request
- The response object
- The most important rule: check response.ok
- A POST request with JSON
- Sending form data and files
- Query strings with URLSearchParams
- Error handling
- Cancelling requests and timeouts
- Race conditions in search
- Cookies and credentials
- CORS in one page
- Common mistakes
- How to say it in an interview
- Key words
What fetch is
fetch is the built-in function for making HTTP requests from JavaScript. It returns a promise (Lesson 69). It works in browsers and in Node.js 18 and later.
A GET request
const response = await fetch("https://api.example.com/products");
const products = await response.json();Two awaits:
fetchresolves when the headers arrive.response.json()reads the body and parses it as JSON. It also returns a promise.
The response object
| Property / method | Meaning |
|---|---|
response.ok | true if the status is 200 to 299 |
response.status | The HTTP status code, such as 200, 404, 500 |
response.headers.get("content-type") | Read a header |
response.json() | Parse the body as JSON |
response.text() | Read the body as text |
response.blob() | Read the body as a file (images, downloads) |
The body can only be read once.
The most important rule: check response.ok
fetch only rejects on network failure (no internet, DNS error, request blocked). A 404 or 500 is still a successful fetch. You must check yourself:
async function getJson(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`Request failed: ${response.status} ${response.statusText}`);
}
return response.json();
}A small helper like this is used in almost every project.
A POST request with JSON
const newUser = await getJson("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Sam", email: "sam@example.com" })
});method: GET is the default. Others: POST, PUT, PATCH, DELETE (Part 15).headers: tell the server the body is JSON.body: must be a string for JSON, so useJSON.stringify.
Sending form data and files
const form = document.querySelector("#profile-form");
const formData = new FormData(form); all named fields, including files
await fetch("/api/profile", {
method: "POST",
body: formData
});Do not set Content-Type yourself for FormData. The browser sets it, including a special "boundary" value the server needs.
Query strings with URLSearchParams
Building URLs by hand breaks when values contain spaces or &. Use URLSearchParams:
const params = new URLSearchParams({ q: "red shoes", page: "2" });
const url = `/api/search?${params}`; "/api/search?q=red+shoes&page=2"
const current = new URLSearchParams(window.location.search);
current.get("page");For a single value, encodeURIComponent(value) also works.
Error handling
try {
const data = await getJson("/api/orders");
render(data);
} catch (error) {
showMessage("Could not load your orders. Please try again.");
console.error(error);
}Show users a friendly message; log the details for yourself.
Cancelling requests and timeouts
An AbortController cancels a request:
const controller = new AbortController();
fetch("/api/report", { signal: controller.signal })
.catch((err) => {
if (err.name === "AbortError") console.log("Cancelled");
});
controller.abort();Timeout (modern browsers and Node.js):
await fetch("/api/slow", { signal: AbortSignal.timeout(5000) });If it takes longer than 5 seconds, it rejects with a TimeoutError.
Use cancelling when the user leaves the page or component, or starts a new search.
Race conditions in search
A user types "re", then "red". Two requests go out. If the "re" response arrives after the "red" response, the page shows the wrong results. This is a race condition.
Fix: cancel the previous request when starting a new one:
let controller;
async function search(text) {
controller?.abort();
controller = new AbortController();
try {
const results = await getJson(`/api/search?q=${encodeURIComponent(text)}`, {
signal: controller.signal
});
renderResults(results);
} catch (err) {
if (err.name !== "AbortError") showError(err);
}
}Combine with debounce (Lesson 78) so you do not send a request for every key press. This exact scenario is a favourite interview question.
Cookies and credentials
- Requests to the same origin (same protocol, domain and port) send cookies automatically.
- To send cookies to a different origin, add
credentials: "include", and the server must allow it.
CORS in one page
Browsers apply the same-origin policy: a page can only read responses from its own origin unless the other server explicitly allows it.
CORS (Cross-Origin Resource Sharing) is how a server gives that permission, using response headers such as Access-Control-Allow-Origin. For some requests (for example JSON POSTs or custom headers), the browser first sends an automatic preflight request with the OPTIONS method to ask permission.
Key points:
- A "CORS error" means the server did not allow your origin. It is fixed on the server, not in front end code.
- CORS is enforced by browsers. Tools like curl and other servers ignore it.
- Part 15 covers CORS headers in detail.
Common mistakes
- Not checking
response.ok. - Forgetting
JSON.stringifyor theContent-Typeheader for JSON bodies. - Setting
Content-Typemanually for FormData. - Forgetting to
await response.json(). - Building query strings without encoding.
- Ignoring race conditions in search and autocomplete.
How to say it in an interview
"fetch returns a promise that resolves when headers arrive and only rejects on network errors, so I always check response.ok and throw for 4xx and 5xx, usually in a small helper. For JSON I stringify the body and set the Content-Type; for FormData I let the browser set it. I build query strings with URLSearchParams. I use AbortController to cancel requests and AbortSignal.timeout for timeouts, and in search boxes I debounce and abort the previous request to avoid race conditions. CORS errors are fixed on the server by allowing the origin."
Key words
| Word | Meaning |
|---|---|
| fetch | The built-in function for HTTP requests |
| Response | The object describing the server's reply |
| Status code | A number describing the result, such as 200 or 404 |
| FormData | An object holding form fields and files |
| URLSearchParams | A tool to build and read query strings |
| AbortController | A way to cancel a request |
| Race condition | A bug caused by results arriving in an unexpected order |
| Origin | Protocol + domain + port |
| CORS | Rules that let a server allow other origins to read its responses |
| Preflight | An automatic OPTIONS request asking permission first |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.