Getting Started With Axios: A Popular Promise-Based HTTP Client
Mục lục bài viết
Getting Started With Axios: A Popular Promise-Based HTTP Client
Learn the key features provided by Axios, and how you can use them in your web applications.
Axios is a popular promise-based HTTP client for the browser and Node.js. On the server-side (Node.js), it uses the native Node.js HTTP module, while on the client-side (browser) it uses XMLHttpRequests.
I will demonstrate the key features offered by Axios in detail so that you can easily understand them, and start utilizing them in your projects, and improve your experience in making API calls in your web applications. Beginners and experienced developers can benefit from this article.
Advantages of Using Axios Over Fetch API
Modern web browsers ship with the Fetch API, but there are various reasons that give Axios an edge. The major difference is how the two libraries handle the HTTP errors. While using the Fetch API, if a server returns a 4xx or 5xx series error, then the catch()
callback will not be triggered. You have to check the status code in the response object in order to determine if the request was successful. On the other hand, Axios will reject the request promise if one of these error codes gets returned from the server.
The second difference is, Fetch doesn’t send cookies back (by default) to the server when performing a request. You have to explicitly provide an option in order to include the cookies. On the other hand, Axios will automatically send cookies in each request you make.
The third difference is, Fetch doesn’t provide any support for monitoring the upload progress, which may end up being a show-stopper for you if you deal with multiple file uploads. On the other hand, Axios provides callback functions to monitor the progress of upload and download. You can use the onUploadProgress()
and onDownloadProgress()
to display the progress in your application UI.
Installing Axios
You can install Axios in the following ways:
- Using NPM
- Using Yarn
- Using Bower
- Using CDN
1. Using NPM
Execute the following command to install Axios:
npm install axios
2. Using Yarn
Execute the following command to install Axios:
yarn add axios
3. Using Bower
Execute the following command to install Axios:
bower install axios
4. Using CDN
Include the following script to use Axios from jsDelivr:
Or, include the following script to use Axios from unpkg:
Request Methods Provided By Axios
Following are the basic functions provided in Axios for making HTTP requests.
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]])
Request Options Provided By Axios
Axios provides a ton of options that you can pass while making a request. Here is a list of the most commonly used options:
- baseURL — if specified, will be prepended to any relative URL you use.
- headers — an object with key-value pairs.
- params — an object with key-value pairs that is sent with the request. It should be a plain object or a URLSearchParams object.
- responseType — indicates the type of data that the server will respond with. Valid options are ‘arraybuffer’, ‘document’, ‘json’, ‘text’, ‘stream’.
- auth — indicates that HTTP Basic auth should be used to connect to a proxy by supplying the necessary credentials (username and password).
Response Objects Provided by Axios
When you send an HTTP request to a remote server, you will get a response back with specific information (if the request is fulfilled). The received response, according to Axios documentation, contains the following information.
- data — the response that was provided by the server.
- status — the HTTP status code from the server response.
- statusText — the HTTP status message from the server response.
- headers — the HTTP headers that the server responded with. All header names are lowercased and can be accessed using bracket notation. Example:
response.headers['content-type']
. - config —the config that was provided to Axios for the request.
- request — the request that generated this response. It is the last ClientRequest instance in Node.js (in redirects), and an XMLHttpRequest instance in the browser.
Sending GET Request To Server
Axios provides a GET method to send an HTTP request to the server. The first parameter accepts the target URL (to which the request will be sent). The second parameter accepts an object of multiple key-value pairs (which we call options). In this example, we’ll use the params
option to send some data to the server. This params
option can again contain multiple key-value pairs.
Refer to the following code snippet to understand how you can send a GET request to the server, get back some responses, and catch errors.
Sending POST Request To Server
Axios provides a POST method to send an HTTP request to the server. The first parameter accepts the target URL (to which the request will be sent). The second parameter accepts an object of multiple key-value pairs. And, the third parameter accepts an object (which we call options). In this example, we’ll use the second parameter to send some data to the server.
Refer to the following code snippet to understand how you can send a POST request to the server, get back some responses, and catch errors.
Using Async and Await Instead of Promises
If you wish to use the async and await functionality instead of promises (then()
and catch()
blocks), you can do so in a few easy steps.
Refer to the following code snippet to understand how you can use async and await to handle HTTP requests.
Sending Multiple Concurrent Requests
Axios provides a feature to send multiple requests to the server at the same time. You can use the Promise.all()
function to pass an array of HTTP requests. When all the requests get fulfilled, it will produce a single promise which will contain the response objects for each request. To get the response for each request, you can use the index of the request array.
Refer to the following code snippet to understand how you can use the Promise.all()
function to send multiple concurrent requests.
Dealing With Failed HTTP Requests
If your submitted HTTP request fails, Axios will catch the error, and store that in an error object. That object will contain a detailed set of information that will help you find the exact location of the error.
Refer to the following code snippet to understand how you can handle errors by using the error object.
Transforming The Requests and Responses
By default, Axios converts the requests and responses to JSON format. But you can still override this behaviour and apply your own transformation format by transformRequest()
and transformResponse()
functions. These become handy when certain APIs supports only XML or CSV formats.
The
transformRequest()
function is only applicable for the following request methods: ‘PUT’, ‘POST’, ‘PATCH’ and ‘DELETE’.
Refer to the following code snippet to understand how you can transform the requests and responses.
Kudos! You have completed learning the key features provided by Axios. Now you can go ahead and start integrating Axios in your current or upcoming projects.
If you enjoyed reading this post and have learnt something new, then please give a clap, share it with your friends, and follow me to get updates for my upcoming posts. You can connect with me on LinkedIn.