OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

How to Make HTTP Requests with Axios

Michiel Mulders
December 10th, 2020 · 5 min read

Sending an HTTP request to an API is one of the most common things a developer does. However, there are many ways to send an API request. We can use a command-line tool such as cURL, use the browser’s native Fetch API, or install a package such as Axios.

Axios is an amazing tool for sending HTTP requests to your API. All popular browsers support Axios. You can use the package for your backend server, load it via a CDN, or require the package in your frontend application.

This article explores the following topics related to Axios:

  1. How to send basic CRUD requests to your API with Axios?
  2. How to send simultaneous requests?
  3. How to intercept requests and responses with Axios?
  4. How to configure XSRF protection for Axios requests?
  5. Which are the best Axios libraries?
  6. Why would you choose Axios over the Fetch API?

Before we start, let’s take a look at the different installation options.

Installation

There are different ways to install Axios, as mentioned in the introduction.

  • Via NPM: npm i --save axios
  • Via CDN through a script tag: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

For this tutorial, we’ll use the NPM option.

1npm i --save axios

Next, we need to create a new project to experiment with Axios.

1npm init -y

Following, let’s create a file called index.js in the root of your project.

1touch index.js

OK? We’re all set!

Exploring the Axios object

Let’s first learn how we can send a request with Axios and how the response looks like.

First of all, the Axios object exposes different methods that we can use to send specific requests. The below methods are aliases for all supported request methods.

  • axios.get(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])
  • axios.delete(url[, config])
  • axios.request(config)
  • axios.head(url[, config])

However, we can also pass an options object directly to the Axios instance. This options object specifies all details for the request we want to send. It’s an alternative to using one of the aliases. The example below illustrates a GET request. Also note how you can add custom headers to your request. We can also add a more standard header, such as Content-Type: application/json.

1const options = {
2 url: 'https://jsonplaceholder.typicode.com/todos/1',
3 method: 'get',
4 headers: {'X-Custom-Header': 'foobar'}
5}

Axios basics: Sending CRUD API requests

In this section, let’s take a look at how we can send basic CRUD requests.

We’ll be using a publicly available JSON REST API for sending and retrieving data. The URL for this API is: https://jsonplaceholder.typicode.com/todos. This API returns TODO data using the following format.

1{
2 userId: 1,
3 id: 1,
4 title: 'my todo',
5 completed: false
6}

Now, let’s load the Axios object. We can require the object directly into our index.js file.

1const axios = require('axios');

All good? Let’s learn how to send CRUD requests.

GET Request with Axios

We can send a GET request using the axios.get(url[, config]) method. As the first argument, we pass the URL for our API. Note that the URL ends with /todo/1. We want to retrieve the TODO object with id 1.

As we are using the async/await syntax, we have to wrap the request by a try-catch block. Don’t forget to call the function that encompasses the try-catch block.

1const getRequest = async () => {
2 try {
3 const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
4 console.log(response.data);
5 } catch (err) {
6 console.error(err);
7 }
8};
9
10getRequest()

We capture the retrieved result in the response variable. The Axios response object contains the following properties.

1{
2 // `data` is the response that was provided by the server
3 data: {},
4
5 // `status` is the HTTP status code from the server response
6 status: 200,
7
8 // `statusText` is the HTTP status message from the server response
9 statusText: 'OK',
10
11 // `headers` the HTTP headers that the server responded with
12 // All header names are lower cased and can be accessed using the bracket notation.
13 // Example: `response.headers['content-type']`
14 headers: {},
15
16 // `config` is the config that was provided to `axios` for the request
17 config: {},
18
19 // `request` is the request that generated this response
20 // It is the last ClientRequest instance in node.js (in redirects)
21 // and an XMLHttpRequest instance in the browser
22 request: {}
23}

As the console.log statement in our example snippet prints the data field, we get the following JSON result.

1{
2 userId: 1,
3 id: 1,
4 title: 'delectus aut autem',
5 completed: false
6}

Now we understand how we can send a request and retrieve response data, let’s take a look at different HTTP methods.

POST Request with Axios

Following, let’s send a POST request.

  • axios.post(url[, data[, config]])

Here’s the code snippet that shows how you can pass data with your POST request.

1const postRequest = async () => {
2 const newTodo = {
3 userId: 1,
4 title: 'Wash my hands',
5 completed: false
6 }
7
8 try {
9 const resp = await axios.post('https://jsonplaceholder.typicode.com/todos', newTodo);
10 console.log(resp.data);
11 } catch (err) {
12 console.error(err);
13 }
14}
15
16postRequest()

PUT Request with Axios

The PUT method allows you to update an entire object.

  • axios.put(url[, data[, config]])

Here’s the code snippet.

1const putRequest = async () => {
2 // Update TODO object with ID 1
3 const updatedTodo = {
4 id: 1,
5 userId: 1,
6 title: 'Updated task title',
7 completed: true
8 }
9
10 try {
11 const resp = await axios.put('https://jsonplaceholder.typicode.com/todos/1', updatedTodo);
12 console.log(resp.data);
13 } catch (err) {
14 console.error(err);
15 }
16}
17
18putRequest()

DELETE Request with Axios

The DELETE method allows you to remove a resource.

  • axios.delete(url[, config])

Below, you find an example.

1const deleteRequest = async () => {
2 try {
3 const resp = await axios.delete('https://jsonplaceholder.typicode.com/todos/1')
4 console.log(resp.data);
5 } catch (err) {
6 // Handle Error Here
7 console.error(err);
8 }
9}
10
11deleteRequest()

Done! We’ve covered all CRUD operations. Let’s explore how we can send simultaneous requests.

Sending simultaneous requests with Axios

Axios provides a similar alternative to the Fetch API’s Promise.all() method: axios.all(). This method accepts an array of Axios requests. If all requests finish successfully, we receive an array that contains all responses.

Let’s take a look at how we can request multiple TODO items.

1const multipleRequests = () => {
2 axios.all([
3 axios.get('https://jsonplaceholder.typicode.com/todos/1'),
4 axios.get('https://jsonplaceholder.typicode.com/todos/2')
5 ])
6 .then(responseArray => {
7 //this will be executed only when all requests are successful
8 console.log('=> Request ID: ', responseArray[0].data.id);
9 console.log('=> Request ID: ', responseArray[1].data.id);
10 });
11}
12
13multipleRequests()
14
15// logged output:
16// => Request ID: 1
17// => Request ID: 2

As you can see, the responseArray variable contains all responses.

If you don’t like using a response array, we can immediately destructure this array as shown in the example below.

1const multipleRequests = async () => {
2 // Use destructuring and await syntax
3 const [req1, req2] = await axios.all([
4 axios.get('https://jsonplaceholder.typicode.com/todos/1'),
5 axios.get('https://jsonplaceholder.typicode.com/todos/2')
6 ])
7}
8
9multipleRequests()

Axios request and response intercepting

Axios provides us with some exciting functionality to intercept both requests and responses. It allows us to intercept the request or response object before they are handled by then or catch. This functionality gives us many possibilities, such as:

  • Automatically adding headers for each request object like authorization headers
  • Transporting response errors to a monitoring tool for analysis
  • Modifying a response object to a different format

The below interceptor example shows how we can modify the request with an extra property and log some useful data. Next, we send a request to check if the interceptor works.

We can access interceptors directly from the imported axios object. Using the use method, we can overwrite the default behaviour with our custom logic.

1axios.interceptors.request.use(config => {
2 config.name = 'my-axios-app'
3 console.log(`Sending ${config.method} request to: ${config.url}`);
4
5 return config;
6}, error => {
7 return Promise.reject(error);
8});
9
10// send GET request
11axios.get('https://jsonplaceholder.typicode.com/todos/1')

Furthermore, let’s log error data and add a timestamp to the error object when the request fails. Here, you can add code to send error data to a frontend monitoring tool, such as OpenReplay.

To test the response interceptor, let’s request a TODO with a non-existing ID.

1axios.interceptors.response.use(response => {
2 return response;
3}, error => {
4 console.log('Request failed for: ', error.config.url)
5 error.timestamp = Date.now()
6 return Promise.reject(error);
7});
8
9// send an incorrect GET request
10const invalidRequest = async () => {
11 try {
12 const resp = await axios.get('https://jsonplaceholder.typicode.com/todos/incorrect-id')
13 } catch (error) {
14 console.log('Something went wrong at timestamp: ', error.timestamp)
15 }
16}
17
18invalidRequest()

Monitor bad and slow requests in production

Debugging Axios requests and responses in production may be challenging and time consuming. OpenReplay is an open-source session replay stack for developers. It helps you replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder.

OpenReplay Frontend Monitoring

OpenReplay helps to quickly get to the root cause by reproducing issues as if they happened in your own browser. It also monitors your frontend performance by capturing key metrics such as time to interactive, page load time, memory consumption and slow network requests as well as Redux, VueX and NgRx actions/state. Start monitoring your web app for free.

Does Axios support XSRF headers?

“Cross-Site Request Forgery is one of the most popular ways of exploiting a server. It attacks the server by forcing the client to perform an unwanted action. This attack targets applications where the client/user is already logged in. It mainly changes the state of the server by making inadvertent updates or transfer of data.”

Luckily, Axios provides protection against cross-site request forgery (XSRF). To prevent this type of attack, we can configure an XSRF cookie and header via the options object. This is how you can achieve it.

1const options = {
2 url: 'https://jsonplaceholder.typicode.com/todos',
3 method: 'post',
4 data: addTodo,
5 xsrfHeaderName: 'X-XSRF-TOKEN',
6 xsrfCookieName: 'XSRF-TOKEN'
7};
8
9// send the request by passing the options object
10await axios(options);

That’s it!

Which are the best Axios libraries?

Axios is so popular among developers that a whole ecosystem of third-party libraries has been created. Many libraries modify the Axios source code or help you with specific tasks. For example, the axios-response-logger library helps you with various ways of logging Axios responses using interceptors.

Here’s an overview of popular Axios libraries:

  • vue-axios: A small wrapper for integrating Axios to Vuejs
  • redux-axios-middleware: Redux middleware for fetching data with axios HTTP client
  • axios-api-versioning: Adds easy-to-manage API versioning to Axios
  • react-hooks-axios: This library adds custom React Hooks for Axios
  • axios-logger: When you send a request in nodejs, you need to show the log to the console. This library display the necessary information while communicating with the server. Very similar to the axios-response-logger library.
  • jest-mock-axios: This library provides functionality to mock Axios requests for unit testing with Jest.

Axios vs. Fetch API: Which is best?

To conclude this article, let’s provide you with some specific arguments to choose Axios over the browser’s Fetch API. Both solutions work well. However, Axios focuses on ease of use while not everything is as straightforward using the Fetch API.

Here are five arguments why you would choose Axios:

  1. Axios lets you quickly configure the timeout property.
  2. Axios’ syntax is more straightforward. For instance, it uses aliases.
  3. Axios provides an easy way to track upload progress via its request config.
  4. Axios interceptors are a great feature to automate specific tasks for requests.
  5. Axios supports automatic JSON stringification when sending requests. While using the Fetch API, we have to do this manually.

On the other hand, we’re loading a library into our project while the Fetch API is already there. In the end, the Axios library won’t increase your total project size by much.

In the end, it’s a personal preference! Axios has gained a lot of popularity as it’s a bit more comfortable to use than the browser’s Fetch API.

More articles from OpenReplay Blog

JWT Authentication Best Practices

The importance of securing frontend client, micro-service communication and client-microservice interaction through JSON Web Tokens.

December 4th, 2020 · 12 min read

JavaScript Heap Out Of Memory Error

A quick solution that you can use to fix "Heap Out Of Memory Error" in JavaScript. We lay out the causes and how to prevent them.

November 30th, 2020 · 4 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552