Sub topic 1
Fetching JSON with the Fetch API
Prerequisites
This chapter assumes you know JavaScript promises and async/await, and basic HTTP: methods, status codes, and JSON. You don't need React yet. The next chapters put this code inside components.
What fetch does
fetch(url, options) is a browser function (also available in Node 18+) that sends an HTTP request. It returns a promise that resolves to a Response object once the server's headers arrive. The body is not read yet.
To get JSON, call response.json(). This is a second promise, because the body can still be streaming in. It resolves to the parsed value, or rejects if the body is not valid JSON.
async function getUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
return users;
}
getUsers().then((users) => console.log(users.length));The error that fetch does not throw
The promise from fetch rejects only when the request itself fails, for example with no network, a DNS failure, or an abort. A 404 or 500 response still resolves normally. If you skip the status check, you will try to parse an error page as data.
Check response.ok. It is true for status codes 200 to 299.
async function getJson(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
getJson('https://jsonplaceholder.typicode.com/users/1')
.then((user) => console.log(user.name))
.catch((error) => console.error(error.message));The helper getJson has two benefits. Callers get one promise that rejects on network failure, on a bad status, and on invalid JSON. It also takes options, so you can pass an abort signal later.
Sending data
For requests that send data, set the method, a Content-Type header, and a string body. fetch does not serialize objects for you.
async function createPost(title) {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, userId: 1 }),
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
createPost('Hello').then((post) => console.log(post.id));Common mistakes
- Treating a resolved promise as success. Always check
response.ok. - Reading the body twice. A body can be consumed once, so
response.json()followed byresponse.text()throws. Callresponse.clone()first if you need both. - Calling
.json()on an empty body, such as a204 No Contentreply. This rejects with a syntax error. - Forgetting
JSON.stringifyon the request body, which sends the text[object Object].
Exercise
A server answers your request with status 500 and an HTML error page. What does await fetch(url) do, and what does await response.json() do after it?
Show answer
await fetch(url) resolves normally, because the request completed. Calling response.json() then rejects with a syntax error, because the HTML is not valid JSON. Checking response.ok first lets you throw a clear error with the status code instead.
Exercise
Write the options object for a PUT request that sends { "name": "Ada" } as JSON.
Show answer
{ method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Ada' }) }