Deep Insights Into JavaScript’s Fetch API | by Sabesan Sathananthan

Synchronous properties of the Response object

After the fetch() request is successful, you get a Response object. It corresponds to the HTTP response of the server.

const response = await fetch(url);

As mentioned earlier, the data contained in Response is read asynchronously through the Stream interface, but it also contains some synchronous attributes, which correspond to the header information of the HTTP response (Headers), which can be read immediately.

In the above example, response.status and response.statusText are the synchronous attributes of Response and can be read immediately.

Response.ok

The Response.ok property returns a boolean value, indicating whether the request is successful, true corresponds to the HTTP request status code 200 to 299, and false corresponds to other status codes.

Response.status

The Response.status property returns a number indicating the status code of the HTTP response (for example, 200, indicating a successful request).

Response.statusText

The Response.statusText property returns a string representing the status information of the HTTP response (for example, after the request is successful, the server returns “OK”).

Response.url

The Response.url property returns the requested URL. If the URL has a redirect, this attribute returns the final URL.

Response.type

The Response.type property returns the type of request. The possible values ​​are as follows:

  • basic: Ordinary, same-origin request.
  • cors: Cross-origin request.
  • error: Network errors, mainly used for service workers.
  • opaque: If the mode attribute of the fetch() request is set to no-cors, this response value will be returned.
  • opaqueredirect: If the redirect attribute of the fetch() request is set to manual, this response value will be returned.

Response.redirected

The Response.redirected property returns a Boolean value, indicating whether the request has been redirected.

Determine whether the request is successful

After fetch() sends a request, there is an important point to note: fetch() will report an error only when there’s a network error or cannot connect. In other cases, no error will be reported, but the request is considered successful.

This means, even if the status code returned by the server is 4xx or 5xx, fetch() will not report an error (i.e. The Promise will not become rejected). Only by obtaining the true status code of the HTTP response through the Responese.status property, can it be determined whether the request is successful. Please see the following example:

In the above example, the Responese.status attribute must be equal to 2xx (200~299) to determine that the request is successful. There’s no need to consider the URL jump (status code is 3xx) because fetch() will automatically convert the jumped status code to 200. Another method is to determine whether Responese.ok is true.

Response.headers property

The Response object also has a Responese.headers property, which points to a Headers object, which corresponds to all the headers of the HTTP response. Headers objects can be traversed using for...of loops.

The Headers object provides the following methods to manipulate headers.

  • Headers.get(): According to the specified key name, return the key-value.
  • Headers.has(): Returns a Boolean value indicating whether a header is included.
  • Headers.set(): Set the specified key name as the new key-value, if the key name does not exist, it will be added.
  • Headers.append(): Add headers.
  • Headers.delete(): Delete the header.
  • Headers.keys(): Return an iterator that can traverse all the keys in turn.
  • Headers.values(): Return an iterator that can traverse all key values ​​in turn.
  • Headers.entries(): Return an iterator that can traverse all key-value pairs in turn ([key, value]).
  • Headers.forEach(): Traverse the headers, in turn. Each header will execute a parameter function.

Some of the above methods can modify the headers because they inherit from the Headers interface. For HTTP responses, modifying headers is of little significance — many headers are read-only and browsers do not allow modification. Among these methods, the most commonly used is response.headers.get(), which is used to read the value of a certain header.

The Headers.keys() and Headers.values() methods are used to traverse the header keys and key values ​​respectively.

The Headers.forEach() method can also traverse all key values ​​and key names.

How to read content

The Response object provides different reading methods according to different types of data returned by the server.

  • response.text(): Get the text string.
  • response.json(): Get the JSON object.
  • response.blob(): Get the binary Blob object.
  • response.formData(): Get the FormData object.
  • response.arrayBuffer(): Get the binary ArrayBuffer object.

The above five reading methods are all asynchronous and all return Promise objects. You must wait until the end of the asynchronous operation to get the complete data returned by the server.

response.text()

response.text() can be used to get text data, such as HTML files.

response.json()

response.json() is mainly used to get the JSON data returned by the server. The example has been given earlier.

response.formData()

response.formData() is mainly used in Service Worker to intercept the form submitted by the user, modify some data, and then submit it to the server.

response.blob()

response.blob() is used to get the binary file.

The above example reads the flower.jpg image file and displays it on the web page.

response.arrayBuffer()

response.arrayBuffer() is mainly used to obtain streaming media files.

The above example is an example where response.arrayBuffer() gets the audio file song.ogg and then plays it online.

Response.clone()

The Stream object can only be read once and it is gone after reading. This means that only one of the five reading methods in the previous section can be used, otherwise, an error will be reported.

let text =  await response.text();
let json =  await response.json();  // Report an error

The above example uses response.text() first and then reads the Stream. After calling response.json() later, there’s no content to read, so an error is reported. The Response object provides the response.clone() method, which creates a copy of the Response object and implements multiple reads.

In the above example, response.clone() made a copy of the Response object and then read the same image twice. The Response object also has a Response.redirect() method, which is used to redirect the Response result to the specified URL. This method is generally only used in Service Worker, so I won’t introduce it here.

Response.body attribute

The Response.body property is the underlying interface exposed by the Response object. It returns a ReadableStream object for user operations. It can be used to read content in blocks. One application is to display the progress of the download.

In the above example, the response.body.getReader() method returns an iterator. The read() method of this traverser returns an object each time, representing the content block read this time. The done attribute of this object is a boolean value, used to judge whether it has been read. The value attribute is an arrayBuffer array, which represents the content of the content block. The value.length attribute is the size of the current block.

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here