Almost every web-based application that does anything substantial performs some kind of HTTP requests. In this article, we will be going over a very popular HTTP client for JavaScript called Axios. Axios is a very easy-to-use and convenient JavaScript library to perform HTTP requests in Node.js. Axios is actually a promise-based HTTP client library that works both in the browser and in a node.js environment. It basically provides a single API for dealing with XMLHttpRequests and node’s HTTP interface, making it very convenient to use. Below are some reason why you would want to use Axios over the traditional Fetch API
- It supports older browsers seamlessly.
- Has a way to set a response timeout and abort requests
- It has built-in CSRF protection
- Allows you to track upload progress
- Performs automatic JSON data transformation
- Works seamlessly in Node.js and Web Browsers
Installation
Before we can start using Axios, we first need to install it. There are multiple ways of doing this:
- Using npm:
$ npm install axios
2. Using bower:
$ bower install axios
3. Using Yarn:
yarn add axios
4. Including it in your page using unpkg.com:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
5. Manual download:
https://github.com/mzabriskie/axios/tree/master/dist
With the installation complete we are going to move on to perform requests. In this example below, we’ll be performing requests to the Calendarific API. We are using the Calendarific API. So get your API key here.
Calendarific provides a JSON API for fetching bank, public, local, national, holidays and observances information for over 200 countries for free. We will start with the most common HTTP methods GET and POST.
// Performing a GET request
const requestUrl = 'https://calendarific.com/api/v2/holidays?country=US&year=2018&api\_key=hsy82&type=national';
axios.get('requestUrl)
.then(function(response){
console.log(response.data); // ex.: { holidays: ''}
console.log(response.status); // ex.: 200
});
// Performing a POST request
axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
.then(function(response){
console.log('saved successfully')
});
Also, for convenience, you will generally use
-
axios.get()
-
axios.post()
(like in jQuery you would use $.get()
and $.post()
instead of $.ajax()
) Axios offers methods for all the HTTP verbs, which are less popular but still used:
-
axios.delete()
-
axios.put()
-
axios.patch()
-
axios.options()
and a method to get the HTTP headers of a request, discarding the body:
-
axios.head()
Performing Multiple Parallel Requests simultaneously
Another really powerful feature of Axios that cannot be understated is the ability to execute multiple requests in parallel, simply provide an array argument to axios.all
.
When all requests are complete, you’ll receive an array containing the response objects in the same order they were sent.
Alternatively, you can use axios.spread to spread the array into multiple arguments. Spread is preferred since dealing with array indexes could be misleading.
In the example below will be using the axios.all
to fetch holidays for 4 countries simultaneously, UK, US, CA and Mexico and spreading the results in multiple variables.
// Requests will be executed in parallel...
axios.all(\[
// Remember to replace the api\_key with a valid one.
axios.get('https://calendarific.com/api/v2/holidays?country=US&year=2019&api\_key=hsy82&type=national'),
axios.get('hhttps://calendarific.com/api/v2/holidays?country=UK&year=2019&api\_key=hsy82&type=national'),
axios.get('hhttps://calendarific.com/api/v2/holidays?country=CA&year=2019&api\_key=hsy82&type=national'),
axios.get('hhttps://calendarific.com/api/v2/holidays?country=MX&year=2019&api\_key=hsy82&type=national')
\])
.then(axios.spread(function (usHolidays, ukHolidays, caHolidays, mxHolidays) {
//... but this callback will be executed only when all requests are complete.
console.log('United States Holidays in 2019', usHolidays.data);
console.log('UK in 2019', ukHolidays.data);
console.log('Canada Holidays in 2019', caHolidays.data);
console.log('Mexico Holidays in 2019', mxHolidays.data);
}));
Finally, we will be going over how to send custom headers with Axios. To do this you need to supply an object containing the headers as the last argument:
var config = {
headers: {'X-My-Custom-Header': 'Header-Value'}
};
axios.get('https://calendarific.com/api/v2/holidays', config);
//or
axios.post('/save', { firstName: 'Marlon' }, config);
Top comments (3)
Typo alert :)
PS. Im pretty sure there is a way to pass query params in form of JSON, instead of keeping URLs long and dirty.
Read more: github.com/axios/axios#request-config
Ouh! And it seems like you can highlight js code in your post by adding
js
(andshell
) to triple backticks - it should be easier to read.Thanks for calling this out.