npm i axios
Axios is a "promise based HTTP client for the browser and node.js"
So what does this mean? What is a promise and what does a HTTP client do?
A promise is used to handle asynchronous operations without the use of callback functions.
With callback functions, operations have to be nested within each other.
( So called Callback Hell)
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
Promises allow for a cleaner code by using .then
.
doSomething()
.then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
A HTTP Client simply handles the HTTP requests and the responses.
*More info on HTTP Requests on previous post.
What is the benefit of using axios over fetch?
Axios allows you to create new instances of axios using custom configuration using the .create()
method.
This allows for a highly effective way to organize all the API requests within a project.
By creating one file or folder that contains all the custom Axios and exporting it,
you can add, remove, edit, refactor all in one place.
You can create an instance by using axios.create()
and feeding the method a custom configuration in the form of an object.
const apiUrl = 'https://some-domain.com'
const authAxios = axios.create({
baseURL: `${apiUrl}API`,
timeout: 1000,
headers: {
Authorization: `Token ${accessToken}`,
},
});
authAxios
.get("/1/kanban/")
.then((res) => console.log("res", res.data))
.catch((err) => console.log(err));
Using .get()
allows you to add additional endpoints, url parameters, or querystrings to the preset baseURL.
.then()
is equal to the one in fetch
except for the fact that you do not have to change the response from json format.
.catch()
handles errors since axios is a promise.