DEV Community

loading...
Cover image for Advanced Axios

Advanced Axios

sstores profile image sstores ・5 min read

What is Axios?

Axios is a promise-based HTTP client which wraps the native javascript HTTP request processes for making requests to external servers from the browser. In other words, when the browser needs information to run code for the client, it may make requests to an outside server and Axios makes this process mor simplified and usable. As is the case with many elements of tech, improvements are constantly made over time, and network requests have had their fair share of makeover throughout the years. As an example, Asynchronous Javascript And XML (AJAX), is a combination of the browser built-in XMLHttpRequest object (to request data from a web server, and JavaScript and HTML DOM (to display or use the data). XMLHttpRequest (XHR) is the native JavaScript API to create AJAX requests. It provides build in methods which give the ability to send network requests between the browser and a server. Axios, is a library that abstracts some of the complexity away from these processes and provides more straightforward methods to handle these requests between browser and server.

Most front end programmers are probably familiar the basic Axios requests, Axios.get, Axios.post, etc. However, the Axios provides additional functionality and more extensive ways to handle requests and processing data. We will go through a non-exhaustive overview of some of these features in this blog.

Making Multiple Requests at Once

Axios.all is a handy function that allows you to make multiple Axios requests at once. Axios.all takes an array of Axios requests and will return an array of the responses of those requests. Keep in mind that if one of the requests fail, by default they will all fail if that possibility is not accounted for. You may choose to return null in the catch block of each individual Axios request. Therefore if one of the requests fail, the promise will still be able to resolve itself.

In order to access and process the responses, which are returned in an array, you may choose to map over the array using the Array.map function. However an alternative could be to use Axios.spread. Axios.Spread will give access to the responses in an array which can then be separated out as necessary. An example of Axios.all and Axios.spread is shown below from storyblok.com:

Alt Text

Although Axios.all and Axios.spread are technically deprecated according to the Axios docs, they are still good to know. You can use Promise.all to a similar effect since axios requests are dealing with promises anyways.

Creating an instance

The Axios.create function can be used to create a new Axios instance. You might want to create a new instance if you need to set custom defaults for your application. Axios comes out of the box with a default instance. It is not necessary to create new instances but can be helpful for specific configurations. For example, masteringjs.io has the following example. You might want to set a timeout on all the Axios requests in a given application. You might do that with the following:

Alt Text

Request Config

When making an Axios request, you have several options of how to build that request. The url is the only required is the only required config option while making a request. If the method such as GET, PUT, POST etc are not specified, it will default to GET. All of these config options are listed on the Axios docs but we will list some helpful ones here.

  • baseURL will be added to the beginning of url unless url is absolute. It can be helpful to set baseURL for an instance of axios to pass relative URLs to methods of that instance.
  • transformRequest is an array of functions that allows you to make changes to the request data before it is sent to the server. This is only applicable for request methods which send data, ie 'PUT', 'POST', and 'PATCH'. The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream.
  • params are the URL parameters to be sent with the request. Params must be a plain object or a URLSearchParams object. data is the data to be sent as the request body. This options is only applicable for request methods PUT, POST, DELETE , and PATCH.
  • timeout specifies the time in milliseconds before the request times out. If the request does take longer than the timeout specifies`, the request will be aborted.

There are also several Node.js only options which can be specified as well.

  • maxContentLength defines the max size in bytes of the http response content allowed in node.js.
  • decompress indicates whether or not the response body should be decompressed automatically. If set to true will also remove the 'content-encoding' header from the responses objects of all decompressed responses. This is a Node only option, as XHR cannot turn off decompression. There are other options that may be utilized with request config listed on the Axios docs. A link is included in the Sources section below.

Response Schema

The response of an Axios request is an object which contains information sent from the server. It includes the following properties:

  • DATA is the response object that was provided by the server. This will include whatever data was requested.
  • STATUS is the HTTP status code from the server response, (ie 200, 404, 500).
  • STATUS TEXT is the HTTP status message from the server response.
  • HEADERS is the object of HTTP headers that the server responded with. All header names are lowercase and are accessible using the bracket notation.
  • CONFIG is the config that was provided to axios for the request
  • REQUEST is the request object that generated this response. It is the last ClientRequest instance in node.js (in redirects) and an XMLHttpRequest instance in the browser

Interceptors

Axios interceptors are functions that Axios calls for every request. You can intercept requests or responses and modify them in some way before they are handled by then or catch. According to masteringjs.io, “You can think of interceptors as Axios' equivalent to middleware in Express or Mongoose.” An example of an interceptor from the Axios docs can be seen below:
Alt Text

In conclusion, Axios is a very useful way to handle requests to a server. For more extensive look at the details above and many more, visit the Axios Docs. Also linked here https://kapeli.com/cheat_sheets/Axios.docset/Contents/Resources/Documents/index
Is a useful Axios“cheat sheet”. Happy coding!

Sources:
https://github.com/axios/axios#request-method-aliases
https://www.pluralsight.com/guides/all-need-to-know-about-axios
https://kapeli.com/cheat_sheets/Axios.docset/Contents/Resources/Documents/index
https://www.storyblok.com/tp/how-to-send-multiple-requests-using-axios
https://masteringjs.io/tutorials/axios/interceptors

Discussion (0)

pic
Editor guide