You will be able to request JSON data from a server in JavaScript using fetch, wait for the response, check for errors, and convert the body into a JavaScript object.
What it is
Fetching JSON means asking a server for data that is formatted as JSON, then reading that data in your JavaScript code. The fetch function sends an HTTP request and returns a Promise. When the promise resolves, you receive a Response object. The response body is not automatically parsed as JSON; you call response.json(), which also returns a promise that resolves to a JavaScript value.
Related terms include HTTP request, response status, promise, async/await, and JSON parsing.
Why it matters
- It lets web pages load user profiles, product lists, or settings without reloading the page.
- It keeps data separate from HTML and JavaScript, making apps easier to maintain.
- It supports modern asynchronous code with
asyncandawait. - It gives access to response metadata such as status codes and headers.
Syntax or steps
The smallest useful pattern is:
const response = await fetch("/api/data");
const data = await response.json();
This code must run inside an async function. In real code, also check response.ok and handle errors.
Example
async function loadUser() {
try {
const response = await fetch("/api/user");
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const user = await response.json();
console.log(user.name);
} catch (error) {
console.error("Could not load user:", error);
}
}
loadUser();
Part by part:
async function loadUser()creates a function that can useawait.await fetch("/api/user")sends a GET request and waits for the server response.response.okis true only for successful HTTP status codes, usually 200 to 299.response.json()reads the response body and parses JSON into an object.try/catchhandles network failures, bad JSON, or thrown HTTP errors.
Common mistakes
- Forgetting
awaitbeforefetchorresponse.json(). Fix it by waiting for both promises. - Assuming
fetchrejects for 404 or 500 responses. It usually resolves; checkresponse.ok. - Not handling invalid JSON. If the server returns HTML or empty text,
response.json()throws; usetry/catch. - Ignoring CORS. If the server does not allow your origin, the request fails; configure server headers or use a same-origin endpoint.
When to use it
Use fetch for most new JavaScript network requests. Use XMLHttpRequest only when you must support very old browsers or need legacy behavior.
| Need | Use | Why |
|---|---|---|
| Modern browser app | fetch | Clean promise-based API and easy async/await. |
| Very old browser | XMLHttpRequest | Broader legacy compatibility. |
| Simple JSON loading | fetch | Short code with response status checks. |
Practice
Guided exercise: write an async function that fetches /api/products, checks response.ok, parses JSON, and logs the first product name.
Expected output if the JSON is [{"name":"Keyboard"}]:
Keyboard
Challenge: modify the request to send a query parameter, such as /api/products?category=tools. Hint: build the URL with a template string or string concatenation.
Quick check
Question: Does fetch automatically throw an error when the server returns a 404 status?
Answer: No. It resolves with a response whose ok property is false, so you must check it yourself.
Summary
Fetching JSON is a two-step asynchronous process: request the resource, then parse the response body. Always check the response status and handle errors so your app fails clearly instead of silently.