Sub topic 3
Reading Response Bodies
This chapter assumes you are comfortable with async/await, know how to call fetch(), and can read response.status and response.ok from the previous chapter. In this chapter you will turn the bytes the server sent into data your code can use.
The Body Arrives After the Headers
The Promise from fetch() resolves when the response headers arrive. The body may still be downloading at that point. To get the body you call one of the Response's reading methods. Each method returns another Promise, so reading a response always involves two awaits: one for fetch() and one for the body.
async function showTitle() {
const response = await fetch('https://api.example.com/posts/1'); // headers ready
const post = await response.json(); // body read and parsed
console.log(post.title);
}
showTitle();Choosing a Reading Method
Each method reads the whole body and gives it back in a different form.
| Method | Resolves to | Typical use |
|---|---|---|
| `json()` | A parsed JavaScript value | API responses |
| `text()` | A string | HTML, CSV, plain text, debugging |
| `blob()` | A `Blob` (bytes plus a MIME type) | Images, files to download or display |
| `arrayBuffer()` | Raw bytes in an `ArrayBuffer` | Binary formats you decode yourself |
| `formData()` | A `FormData` object | Responses encoded as form data (rare) |
Pick the method that matches what the server sends. The Content-Type response header tells you what that is.
json()
json() reads the body as text and then runs JSON.parse on it. If the body is not valid JSON, the Promise rejects with a SyntaxError. This happens often when a server returns an HTML error page or an empty body, for example after a 204 No Content response.
async function loadJson(url) {
const response = await fetch(url);
try {
return await response.json();
} catch (err) {
if (err instanceof SyntaxError) {
console.error('Body was not valid JSON');
}
throw err;
}
}text()
text() decodes the body as UTF-8. It is the safest method when you are not sure what came back, because any body can be read as text.
blob() for Binary Data
A Blob holds binary data together with its MIME type. To display an image you fetched, create an object URL from the blob:
async function showImage(url, imgElement) {
const response = await fetch(url);
const blob = await response.blob();
console.log(blob.type, blob.size); // e.g. "image/png" 20480
const objectUrl = URL.createObjectURL(blob);
imgElement.src = objectUrl;
imgElement.onload = () => URL.revokeObjectURL(objectUrl); // free the memory
}
showImage('https://api.example.com/avatar.png', document.querySelector('img'));Use arrayBuffer() when you need to inspect the individual bytes. You can wrap the result in a typed array such as new Uint8Array(buffer).
Bodies Can Be Read Only Once
A response body is a stream, and reading it uses it up. Once you call any reading method, response.bodyUsed becomes true. Calling a second reading method then rejects with a TypeError.
This is a common error:
async function broken(url) {
const response = await fetch(url);
console.log(await response.text()); // logs the body for debugging
return response.json(); // TypeError: body already used
}If you need the body in two forms, call clone() before reading. The clone has its own copy of the body stream.
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); // true
console.log(data, raw.length);
}
readTwice('https://api.example.com/report');A simpler fix is often to read the body once as text and parse it yourself:
async function readOnce(url) {
const response = await fetch(url);
const raw = await response.text();
const data = raw ? JSON.parse(raw) : null; // also handles empty bodies
return { raw, data };
}Common Mistakes
- Forgetting the second
await.const data = response.json()gives you a pending Promise, not the data. - Calling
json()on a body that is empty or HTML, which causes aSyntaxError. - Reading the body for logging and then trying to read it again.
- Using
text()on binary data such as images, which corrupts the bytes. Useblob()orarrayBuffer()instead.
Exercise
A function calls const data = await response.json(); and then, inside a catch block, calls await response.text() to log what the server actually sent. The log step itself throws. Why, and how would you fix it?
Show answer
The failed json() call has already consumed the body, so bodyUsed is true and text() rejects with a TypeError. Read the body once with text(), log it if needed, and then parse it with JSON.parse inside a try/catch. The other option is to call response.clone() before json() and read the clone's text() in the catch block.
Exercise
Which reading method would you use to fetch a PDF and offer it to the user as a download link, and why?
Show answer
Use blob(). A Blob keeps the binary bytes intact along with the MIME type, and URL.createObjectURL(blob) produces a URL you can assign to a link's href attribute. text() would corrupt the binary data.