Reading JSON
Learn to read the response body with response.json().
The body is read separately
When a fetch call completes, the Response object holds only the status code and headers. The body of the response is a stream and is read with its own methods.
const response = await fetch(url);
const body = await response.text();text() gives the body as plain text. It also returns a Promise, so you put await in front of it. The body is not read until you ask for it; that is why you wait first for fetch, then for the body.
Two awaits
In a fetch request you typically use await twice: the first waits for the request to finish, the second waits for the body to be read.
async function load() {
const response = await fetch(url);
const body = await response.text();
console.log(body);
}Keeping the two steps separate gives you flexibility: you can check response.status first to see whether the request succeeded, then read and use the body. The body can be read only once; a second call to text() throws.
Exercise Read the response and the body
The url variable holds an address. Use await fetch(url) to put the response into a response variable, and await response.text() to put the body into a body variable. Then log body with console.log.
Show example solution
const response = await fetch(url);
const body = await response.text();
console.log(body);
Test yourself
-
Read the body as text
const body = await response.____();Show answer
const body = await response.text(); -
Match methods to their meanings
- fetch(url)
- Sends the request
- response.text()
- Reads the body as text
- response.status
- Gives the status code
-
What does response.text() return?
const body = await response.text();- A Promise
- A number
- An array
- true or false
Show answer
A Promise — Correct! text() returns a Promise; you wait for the result with await.