How to make HTTP requests with Axios
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/
Last updated
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/
Last updated
January 26, 2021 9 min read
Editor’s note: This Axios tutorial was last updated on 26 January 2021.
Axios is a client HTTP API based on the XMLHttpRequest
interface provided by browsers.
In this tutorial, we’ll demonstrate how to make HTTP requests using Axios with clear examples, including how to make an Axios POST request with axios.post()
, how to send multiple requests simultaneously with axios.all()
, and much more.
We’ll cover the following in detail:
If you’re more of a visual learner, check out the video tutorial below:
The most common way for frontend programs to communicate with servers is through the HTTP protocol. You are probably familiar with the Fetch API and the XMLHttpRequest
interface, which allows you to fetch resources and make HTTP requests.
If you’re using a JavaScript library, chances are it comes with a client HTTP API. jQuery’s $.ajax()
function, for example, has been particularly popular with frontend developers. But as developers move away from such libraries in favor of native APIs, dedicated HTTP clients have emerged to fill the gap.
As with Fetch, Axios is promise-based. However, it provides a more powerful and flexible feature set.
Advantages of using Axios over the native Fetch API include:
Request and response interception
Streamlined error handling
Protection against XSRF
Support for upload progress
Response timeout
The ability to cancel requests
Support for older browsers
Automatic JSON data transformation
You can install Axios using:
npm:
The Bower package manager:
Or a content delivery network:
Making an HTTP request is as easy as passing a config object to the Axios function. You can make a POST request using Axios to “post” data to a given endpoint and trigger events.
To perform an HTTP POST request in Axios, call axios.post()
.
Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server.
For a simple Axios POST request, the object must have a url
property. If no method is provided, GET
will be used as the default value.
Let’s look at a simple Axios POST example:
This should look familiar to those who have worked with jQuery’s $.ajax
function. This code is simply instructing Axios to send a POST request to /login
with an object of key/value pairs as its data. Axios will automatically convert the data to JSON and send it as the request body.
Axios also provides a set of shorthand methods for performing different types of requests. The methods are as follows:
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]])
For instance, the following code shows how the previous example could be written using the axios.post()
method:
axios.post
return?Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.
To handle the result, you can use the then()
method, like this:
If the promise is fulfilled, the first argument of then()
will be called; if the promise is rejected, the second argument will be called. According to the documentation, the fulfillment value is an object containing the following information:
As an example, here’s how the response looks when requesting data from the GitHub API:
axios.all
to send multiple requestsOne of Axios’ more interesting features is its ability to make multiple requests in parallel by passing an array of arguments to the axios.all()
method. This method returns a single promise object that resolves only when all arguments passed as an array have resolved.
Here’s a simple example of how to use axios.all
to make simultaneous HTTP requests:
This code makes two requests to the GitHub API and then logs the value of the created_at
property of each response to the console. Keep in mind that if any of the arguments rejects then the promise will immediately reject with the reason of the first promise that rejects.
For convenience, Axios also provides a method called axios.spread()
to assign the properties of the response array to separate variables. Here’s how you could use this method:
The output of this code is the same as the previous example. The only difference is that the axios.spread()
method is used to unpack values from the response array.
Sending custom headers with Axios is very straightforward. Simply pass an object containing the headers as the last argument. For example:
Axios automatically serializes JavaScript objects to JSON when passed to the axios.post
function as the second parameter. This eliminates the need to serialize POST bodies to JSON.
Axios also sets the Content-Type
header to application/json
. This enables web frameworks to automatically parse the data.
If you want to send a preserialized JSON string to axios.post()
as JSON, you’ll need to make sure the Content-Type
header is set.
Although Axios automatically converts requests and responses to JSON by default, it also allows you to override the default behavior and define a different transformation mechanism. This is particularly useful when working with an API that accepts only a specific data format, such as XML or CSV.
To change request data before sending it to the server, set the transformRequest
property in the config object. Note that this method only works for PUT
, POST
, and PATCH
request methods.
Here’s an example of how to use transformRequest
in Axios:
To modify the data before passing it to then()
or catch()
, you can set the transformResponse
property:
HTTP interception is a popular feature of Axios. With this feature, you can examine and change HTTP requests from your program to the server and vice versa, which is very useful for a variety of implicit tasks, such as logging and authentication.
At first glance, interceptors look very much like transforms, but they differ in one key way: unlike transforms, which only receive the data and headers as arguments, interceptors receive the entire response object or request config.
You can declare a request interceptor in Axios like this:
This code logs a message to the console whenever a request is sent then waits until it gets a response from the server, at which point it prints the time the account was created at GitHub to the console. One advantage of using interceptors is that you no longer have to implement tasks for each HTTP request separately.
Axios also provides a response interceptor, which allows you to transform the responses from a server on their way back to the application:
Cross-site request forgery (or XSRF for short) is a method of attacking a web-hosted app in which the attacker disguises himself as a legal and trusted user to influence the interaction between the app and the user’s browser. There are many ways to execute such an attack, including XMLHttpRequest
.
Don't miss a moment with The Replay, a curated newsletter from LogRocket
Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
Use React's useEffect to optimize your application's performance
Switch between multiple versions of Node
Discover how to animate your React app with AnimXYZ
Explore Tauri, a new framework for building binaries
Compare NestJS vs. Express.js
Fortunately, Axios is designed to protect against XSRF by allowing you to embed additional authentication data when making requests. This enables the server to discover requests from unauthorized locations. Here’s how this can be done with Axios:
LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic Axios requests to quickly understand the root cause.
LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, and slow network requests as well as logs Redux, NgRx. and Vuex actions/state. Start monitoring for free.
Another interesting feature of Axios is the ability to monitor request progress. This is especially useful when downloading or uploading large files. The provided example in the Axios documentation gives you a good idea of how that can be done. But for the sake of simplicity and style, we are going to use the Axios Progress Bar module in this tutorial.
The first thing we need to do to use this module is to include the related style and script:
Then we can implement the progress bar like this:
To change the default styling of the progress bar, we can override the following style rules:
In some situations, you may no longer care about the result and want to cancel a request that’s already sent. This can be done by using a cancel token. The ability to cancel requests was added to Axios in version 1.5 and is based on the cancelable promises proposal. Here’s a simple example:
You can also create a cancel token by passing an executor function to the CancelToken
constructor, as shown below:
Axios’ rise in popularity among developers has resulted in a rich selection of third-party libraries that extend its functionality. From testers to loggers, there’s a library for almost any additional feature you may need when using Axios. Here are some popular libraries currently available:
axios-vcr: Record and replay requests in JavaScript
axios-response-logger: Axios interceptor which logs responses
axios-method-override: Axios request method override plugin
axios-extensions: Axios extensions lib, including throttle and cache GET request features
axios-api-versioning: Add easy-to-manage API versioning to Axios
axios-cache-plugin: Helps you cache GET requests when using Axios
axios-cookiejar-support: Add tough-cookie support to Axios
react-hooks-axios: Custom React Hooks for Axios
moxios: Mock Axios requests for testing
redux-saga-requests: Redux-Saga add-on to simplify handling of AJAX requests
axios-fetch: A Web API Fetch implementation backed by an Axios client
axios-curlirize: Log any Axios request as a curl command in the console
axios-actions: Bundle endpoints as callable, reusable services
mocha-axios: HTTP assertions for Mocha using Axios
axios-mock-adapter: Axios adapter that allows you to easily mock requests
axios-debug-log: Axios interceptor of logging request and response with debug library
redux-axios-middleware: Redux middleware for fetching data with Axios HTTP client
axiosist: Axios-based supertest: convert nNode.js request handler to Axios adapter, used for Node.js server unit test
When it comes to browser support, Axios is very reliable. Even older browsers such as IE 11 work well with Axios.
Chrome
Firefox
Safari
Edge
IE
11
There’s a good reason Axios is so popular among developers: it’s packed with useful features. In this post, we’ve taken a good look at several key features of Axios and learned how to use them in practice. But there are still many aspects of Axios that we’ve not discussed. So be sure to check out the Axios GitHub page to learn more.
Do you have some tips on using Axios? Let us know in the comments!
While Axios has some features for debugging requests and responses, making sure Axios continues to serve resources to your app in production is where things get tougher. If you’re interested in ensuring requests to the backend or 3rd party services are successful, try LogRocket. https://logrocket.com/signup/