One of the fundamental tasks of a frontend application is to communicate with servers through the HTTP protocol. JavaScript can send network requests to the server and load new information whenever needed without reloading the page.
The term for that kind of operation is Asynchronous JavaScript And XML (AJAX), which uses the XMLHttpRequest object to communicate with the servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.
In this guide, we will be looking at how to make a network request to get information from the server asynchronously with the fetch() API and Axios and learn how they can be used to perform different operations.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch()
method that provides an easy, logical way to fetch resources asynchronously across the network.
The fetch()
method takes one mandatory argument—the path to the resource you want to fetch—and returns a Promise that resolves with an object of the built-in Response class as soon as the server responds with headers.
The code below demonstrates a very basic fetch request in which we are fetching a JSON file across the network.
1fetch('examples/example.json')
2 .then((response) => {
3 // Do stuff with the response
4 })
5 .catch((error) => {
6 console.log('Looks like there was a problem: \n', error);
7 });
The second argument that the fetch()
method takes is the request object.
1{
2 method: 'POST', // *GET, POST, PUT, DELETE, etc.
3 mode: 'cors', // no-cors, *cors, same-origin
4 cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
5 credentials: 'same-origin', // include, *same-origin, omit
6 headers: {
7 'Content-Type': 'application/json'
8 },
9 redirect: 'follow', // manual, *follow, error
10 referrerPolicy: 'no-referrer', // no-referrer, *client
11 body: JSON.stringify(data) // body data type must match "Content-Type" header
12}
Once a Response
is retrieved, the returned object contains the following properties:
response.body
: A simple getter exposing a ReadableStream of the body contentsresponse.bodyUsed
: Stores a Boolean that declares whether the body has been used in a response yetresponse.headers
: The headers object associated with the responseresponse.ok
: A Boolean indicating whether the response was successful or notresponse.redirected
: Indicates whether or not the response is the result of a redirectresponse.status
: The status code of the responseresponse.statusText
: The status message corresponding to the status coderesponse.type
: The type of the responseresponse.url
: The URL of the responseThere are a number of methods available to define the body content in various formats:
response.json()
: Parse the response as JSONresponse.text()
: Read the response and return as textresponse.formData()
: Return the response as FormData objectresponse.blob()
: Return the response as Blobresponse.arrayBuffer()
: Return the response as ArrayBufferAxios is a Javascript library used to make http requests from node.js
or XMLHttpRequests
from the browser, and it supports the Promise API that is native to JS ES6.
Some core features of Axios, according to the documentation, are:
Axios does not come as a native JavaScript API, so we will have to manually import into our project. To get started, we will have to include the following commands:
Using cdn
1<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Using npm
1npm install axios
Using bower
1bower install axios
And make a request as follows:
1axios.get('examples/example.json')
2 .then((response) => {
3 // handle success
4 console.log(response);
5 })
6 .catch((error) => {
7 // handle error
8 console.log(error);
9 })
Axios also provides more functions to make other network requests as well, matching the HTTP verbs that you wish to execute, such as:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
You can check out the comprehensive request config in the official documentation.
The response from a request contains the following information:
response.data
: The response provided by the serverresponse.status
: The HTTP status code from the server responseresponse.statusText
: HTTP status message from the server responseresponse.headers
: The headers that the server responded withresponse.config
: The config that was provided to axios
for the requestresponse.request
: The request that generated this responseWe're now familiar with the definitions and usage of axios
and fetch()
. Let's focus our attention on how to perform some real world operations with both Axios and Fetch.
There is a two-step process when handling JSON data with fetch()
. First, we have to make the actual request, and then we call the .json()
method on the response.
1fetch("examples/example.json") // first step
2 .then(response => response.json()) // second step
3 .then(data => {
4 console.log(data)
5 })
6 .catch(error => console.error(error))
Axios automatically transforms JSON data once the request is resolved, so we do not have to do much here.
1axios
2 .get("examples/example.json")
3 .then(response => {
4 console.log(response.data)
5 })
6 .catch(error => {
7 console.log(error)
8 })
Handling errors with Axios is pretty straightforward because bad responses (like 404 or 500) will reject the promise.
1axios
2 .get("examples/example.json")
3 .then(response => {
4 console.log("response", response)
5 })
6 .catch(error => {
7 if (error.response) {
8 // The request was made and the server responded with a status code
9 // that falls out of the range of 2xx
10 console.log(error.response.data)
11 } else if (error.request) {
12 // The request was made but no response was received
13 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
14 // http.ClientRequest in node.js
15 console.log(error.request)
16 } else {
17 // Something happened in setting up the request that triggered an Error
18 console.log("Error", error.message)
19 }
20 console.log(error.config)
21 })
Evaluating the success of responses is particularly important when using fetch()
because bad responses (like 404 or 500) still resolve. The only time a fetch promise will reject is if the request was unable to complete. The code would look something like this:
1fetch("examples/example.json")
2 .then(response => {
3 if (!response.ok) {
4 throw Error(response.statusText)
5 }
6 return response.json()
7 })
8 .then(data => {
9 console.log(data)
10 })
11 .catch(error => console.error(error))
One of the key features of Axios is its ability to intercept HTTP requests. Interceptors can be really helpful when we want to examine or change HTTP requests from our application to the server, such as retrieving a token from local storage and including it in all requests.
1// Add a request interceptor
2axios.interceptors.request.use(
3 function(config) {
4 // Do something before request is sent
5 return config
6 },
7 function(error) {
8 // Do something with request error
9 return Promise.reject(error)
10 }
11)
12
13// Add a response interceptor
14axios.interceptors.response.use(
15 function(response) {
16 // Do something with response data
17 return response
18 },
19 function(error) {
20 // Do something with response error
21 return Promise.reject(error)
22 }
23)
24
25// sent a GET request
26axios.get("examples/example.json").then(response => {
27 console.log(response.data)
28})
By default, fetch()
does not provide a way to intercept HTTP requests. We can overwrite the global fetch()
method and define our own interceptor, like this:
1fetch = (originalFetch => {
2 return (...arguments) => {
3 const result = originalFetch.apply(this, arguments)
4 return result.then(console.log("Request was sent"))
5 }
6})(fetch)
7
8fetch("examples/example.json")
9 .then(response => response.json())
10 .then(data => {
11 console.log(data)
12 })
In this guide, we have looked at Fetch and Axios and checked out some real-world operations. While Axios is widely supported among the majority of browsers and can also be used in the nodejs environment, Fetch, on the other hand, isn't widely supported among old browsers. If you need to support older browsers, a polyfill is available.
Here are some useful links to learn more about various use-cases of both Axios and Fetch: