Axios.js
Overview
Axios is a Javascript library used to make HTTP requests similar to fetch(). It is supported by many different browsers including Chrome, Firefox and IE. However Axios comes with certain features that fetch does not have.
How to use
To install Axios to your project run the command
npm instal axios --save
After installing Axios successfully you just need to import it wherever you use it.
import axios from 'axios'
After importing it you basically use it like you would fetch.
axios.get('http://localhost/api').then(res => res.json())
Interceptors
Axios comes with something called interceptors which is useful when you want to examine or change HTTP requests.
axios.interceptors.request.use(config => {
console.log('Request sent');
return config;
});
// sent a GET request
axios.get('https://localhost/api')
.then(response => res.json());
In the code above the console.log is run every time before a HTTP request is sent. Fetch does not come with an interceptor so you would have to make a way around it instead.
Simultaneous Requests
Axios provides a way to make simultaneous requests using all() and spread().
axios.all([
axios.get('https://localhost/api/1'),
axios.get('https://localhost/api/2')
])
.then(axios.spread((res1, res2) => {
// Both requests are now complete
console.log(res1);
console.log(res2);
}));
By using all() and spread() you can make multiple requests at the same time and handle the results using spread(). It is possible to do this with fetch but the use of async is required.
Conclusion
Using Axios is similar to fetch but it comes with extra features including interceptors and making simultaneous requests. If you do not require the use of the extra features provided by Axios it might be better to stick with fetch instead. Axios is easy to use but there is also no reason not to stick with fetch.