The Fetch API is a modern approach to making asynchronous network requests in the browser. It offers a more streamlined and intuitive way to handle AJAX calls compared to the older XMLHttpRequest (XHR) approach. In this article, we will explore the basics of using the Fetch API and the features it provides.

Introduction to the Fetch API

Introduced as a standardized replacement for XHR, the Fetch API uses Promises as a building block for asynchronous network requests. It offers a more elegant and intuitive syntax for making network calls, making it easier to work with and understand.

Fetch API has good support across major browsers except for Internet Explorer. However, you can use a polyfill such as the one provided by GitHub to use fetch on any browser.

Using Fetch

To make a simple GET request using Fetch, you can use the fetch() function with the URL of the resource you want to fetch. For example:

fetch('/file.json')

This will make an HTTP request to retrieve the file.json resource from the same domain.

To actually access the content of the response, you can use the then() method to handle the result of the promise returned by fetch(). For example:

fetch('./file.json')
 .then(response => response.json())
 .then(data => console.log(data))

This code snippet fetches the file.json resource and logs its content to the console.

Catching Errors

Since fetch() returns a promise, you can use the catch() method to handle any errors that occur during the execution of the request. For example:

fetch('./file.json')
.then(response => {
 //...
})
.catch(err => console.error(err))

You can also handle errors within the then() callback by checking the response’s ok property. For example:

fetch('./file.json')
.then(response => {
 if (!response.ok) { throw Error(response.statusText) }
 return response
})
.then(response => {
 //...
})

Response Object

The Response Object returned by a fetch() call contains all the information about the request and response of the network request.

Metadata

headers

You can access the HTTP headers returned by the request using the headers property of the response object. For example:

fetch('./file.json').then(response => {
 console.log(response.headers.get('Content-Type'))
 console.log(response.headers.get('Date'))
})

status

The status property of the response object represents the HTTP response status. The status can be any valid HTTP status code. For example:

fetch('./file.json').then(response => console.log(response.status))

statusText

The statusText property of the response object represents the status message of the response. If the request is successful, the status is OK. For example:

fetch('./file.json').then(response => console.log(response.statusText))

url

The url property of the response object represents the full URL of the fetched resource. For example:

fetch('./file.json').then(response => console.log(response.url))

Body Content

The response object also provides several methods to access the body content of the response:

  • text(): Returns the body as a string.
  • json(): Returns the body as a JSON-parsed object.
  • blob(): Returns the body as a Blob object.
  • formData(): Returns the body as a FormData object.
  • arrayBuffer(): Returns the body as an ArrayBuffer object.

All of these methods return a promise. For example:

fetch('./file.json')
 .then(response => response.text())
 .then(body => console.log(body))

This code snippet fetches the file.json resource and logs its content as a string.

Request Object

The Request object represents a resource request. It can be created using the new Request() API. For example:

const req = new Request('/api/todos')

The Request object offers read-only properties to inspect the details of the resource request, such as method, url, headers, referrer, and cache. It also exposes methods like json(), text(), and formData() to process the body of the request.

Request Headers

You can set the HTTP request headers using the Headers object provided by Fetch. For example:

const headers = new Headers()
headers.append('Content-Type', 'application/json')

To attach the headers to the request, you can use the Request object. For example:

const request = new Request('./file.json', {
 headers: new Headers({ 'Content-Type': 'application/json' })
})
fetch(request)

POST Requests

Fetch allows you to use any HTTP method in your request, including POST, PUT, DELETE, and OPTIONS. To make a POST request, you can specify the method as ‘post’ in the request options, and pass additional parameters in the header and request body. For example:

const options = {
 method: 'post',
 headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' },
 body: 'name=Flavio&test=1'
}

fetch(url, options).catch(err => {
 console.error('Request failed', err)
})

How to Cancel a Fetch Request

Previously, it was not possible to abort a fetch request once it was initiated. However, now you can use the AbortController and AbortSignal API to handle abort events. To integrate this API, you can pass a signal as a fetch parameter. For example:

const controller = new AbortController()
const signal = controller.signal

fetch('./file.json', { signal })

You can set a timeout that fires an abort event after a specified period of time to cancel the fetch request. For example:

setTimeout(() => controller.abort(), 5 * 1000)

When an abort signal occurs, the fetch promise is rejected with a DOMException named AbortError. You can handle this error using the catch block. For example:

fetch('./file.json', { signal })
 .then(response => response.text())
 .then(text => console.log(text))
 .catch(err => {
 if (err.name === 'AbortError') {
 console.error('Fetch aborted')
 } else {
 console.error('Another error', err)
 }
 })

Looking for more?

If you’re looking for additional features and functionalities built upon Fetch, you might find the Axios JavaScript library to be a better fit for your needs. Axios provides a powerful and user-friendly API for making HTTP requests in both the browser and Node.js.

I hope this article has provided a comprehensive overview of the Fetch API and its functionalities. Use this knowledge to make your asynchronous network requests more efficient and streamlined. Happy coding!