Sub topic 1
Your First Request: How fetch() Works
Prerequisites
This chapter assumes you know JavaScript functions and objects, Promises with async/await, try/catch, and basic HTTP terms such as methods, status codes, and headers. You can run every example in the browser developer tools console.
Calling fetch()
fetch(url) sends an HTTP GET request and returns a Promise right away. The Promise resolves to a Response object when the response headers arrive. The body may still be downloading at that point. This is why reading data takes two steps: you await the response first, then you await the body.
Inspecting the Response
The Response object describes the reply before you read its body:
| Property | Meaning |
|---|---|
| `status` | Numeric code, such as 200 or 404 |
| `ok` | `true` when the status is 200–299 |
| `statusText` | Text that goes with the status, such as "Not Found" |
| `headers` | A `Headers` object; use `headers.get(name)` |
async function inspect(url) {
const response = await fetch(url);
console.log(response.status, response.ok, response.statusText);
console.log(response.headers.get('content-type'));
}
inspect('https://jsonplaceholder.typicode.com/todos/1');Reading Response Bodies
Pick a body method that matches the content. Each one returns a Promise:
json()parses the body as JSON.text()returns the body as a string.blob()returns binary data, such as an image.
async function getTodo(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
return response.json();
}
getTodo(1)
.then((todo) => console.log(todo.title))
.catch((err) => console.error('Request failed:', err.message));You can read a body only once. A second read throws a TypeError, and after the first read response.bodyUsed becomes true. If you need the body in two formats, call response.clone() before reading:
async function readTwice(url) {
const response = await fetch(url);
const copy = response.clone();
const data = await response.json();
const raw = await copy.text();
console.log(response.bodyUsed, data, raw.length); // true, {...}, N
}
readTwice('https://jsonplaceholder.typicode.com/todos/1');Exercise
A request returns status 404. Does await fetch(url) throw? What happens if you then call response.json() twice?
Show answer
No. The Promise resolves with ok set to false and status set to 404. The first json() call reads the body, and it may reject if the 404 body is not valid JSON. The second call rejects with a TypeError because the body has already been used. To read it twice, clone the response first.