When developing a full stack application with outside resources such as an API, we need a way for the front end to communicate with the server in the back end to get some data. There are multiple ways to do this such as using the reacts built in fetch API method and the XMLHttpRequest or we could use jQuery’s AJAX requests. The issue with using AJAX is that there are a lot of components that go with making a request and most of all we would love to distance ourselves from jQuery. Today we will be discussing an alternative, using Axios.
Axios is a promise-based HTTP request library that allows us to interact with rest API's. Because Axios is a promise-based library it supports making asynchronous request so that your browser can function normally while waiting for the request to be handled. We will now talk about how to make HTTP requests using Axios.
When we want to get some data we can make an axios.get() request. The first parameter is a URL to perform the request on. The response that comes back, if the promise is resolved, will be contained in the .then() and will be an object that consists of keys of data, status, status text, and headers. The data key will contain the data we set out to request. Let us look at an example.
In this example, we can attach the HTTP method on axios and just pass in the URL as the parameters then chain on our then and catch on to it. This way is much easier to read and does not take up a lot of space.
If we want to post some data to a specific endpoint, we can use the axios.post() method. The first parameter is a specific URL or endpoint. the second parameter is and object containing the data we want to send to our server.
Because axios utilizes promises, it uses a familiar promise method. We can have multiple request happen simultaneously with the axios.all() method. This method takes in an array of requests and returns and object if both request resolves. even though it can take multiple request we only need to chain on one then() and one catch() to it. Let us look at an example.
In conclusion, Axios is a library used to make HTTP requests. Because of its asynchronous nature we can be sure that our browser can function without interruption while waiting for the request to be resolved. Axios comes with a lot of built in methods that make making these request easy to write.