Response
What is it
const myImage = document.querySelector("img"); const myRequest = new Request("flowers.jpg"); fetch(myRequest) .then((response) => { console.log('response.type =', response.type); console.log('response.url =', response.url); console.log('response.userFinalURL =', response.useFinalURL); console.log('response.status =', response.status); console.log('response.ok =', response.ok); console.log('response.statusText =', response.statusText); console.log('response.headers =', response.headers); });
Common formats to parse Response
response.json()
returns a promise resolved to a JSON objectresponse.text()
returns a promise resolved to raw textresponse.formData()
returns a promise resolved to FormDataresponse.blob()
returns a promise resolved to a Blob (a file-like object of raw data)response.arrayBuffer()
returns a promise resolved to an ArryBuffer (raw generic binary data)
json()
Method
Method of the Response
interface that takes a Response stream and reads it to completion
Despite the method being named json
, the result is not JSON
, but is instead the result of taking JSON as input
and parsing it to produce a JavaScript object
const responseData = await response.json();
Return value
The method returns a Promise
- A
Promise
that resolves to a JavaScript object
Because the return value is a Promise
, you have to await
for the response to become a readable data
- This object could be anything that can be represented by JSON — an
object
, anarray
, astring
, anumber
, etc.