/

Making HTTP Requests with Axios: A Comprehensive Guide

Making HTTP Requests with Axios: A Comprehensive Guide

Axios is a highly popular JavaScript library that allows you to perform HTTP requests in both browser and Node.js platforms. It supports all modern browsers, including IE8 and higher. The library is promise-based, which means you can use async/await syntax to make XHR requests effortlessly. In this blog post, we will cover the basics of Axios and how to use it effectively.

Installation

To use Axios in a Node.js environment, you can simply install it via npm:

1
npm install axios

For browser usage, you can include Axios in your page using a script tag:

1
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Please note that CORS (Cross-Origin Resource Sharing) must be enabled for API calls made from within a browser, otherwise the requests will fail.

The Axios API

Axios provides a simple and intuitive API for making HTTP requests. You can start a request by calling the axios function with the desired options:

1
2
3
4
axios({
url: 'https://dog.ceo/api/breeds/list/all',
method: 'get'
})

This returns a promise that you can resolve with async/await syntax:

1
2
3
4
5
6
7
8
(async () => {
const response = await axios({
url: 'https://dog.ceo/api/breeds/list/all',
method: 'get'
});

console.log(response);
})();

For convenience, Axios also provides shorthand methods for GET and POST requests:

1
2
3
4
(async () => {
const response = await axios.get('https://dog.ceo/api/breeds/list/all');
console.log(response);
})();

Axios supports other HTTP verbs as well, including DELETE, PUT, PATCH, and OPTIONS. Additionally, there is a axios.head() method that allows you to retrieve the HTTP headers of a request, without the response body.

Making GET Requests

Here’s an example of making a GET request using Axios in a Node.js environment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const axios = require('axios');

const getBreeds = async () => {
try {
return await axios.get('https://dog.ceo/api/breeds/list/all');
} catch (error) {
console.error(error);
}
};

const countBreeds = async () => {
const breeds = await getBreeds();

if (breeds.data.message) {
console.log(`Got ${Object.entries(breeds.data.message).length} breeds`);
}
};

countBreeds();

If you prefer using Promises instead of async/await syntax, the code can be written as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const axios = require('axios');

const getBreeds = () => {
try {
return axios.get('https://dog.ceo/api/breeds/list/all');
} catch (error) {
console.error(error);
}
};

const countBreeds = async () => {
const breeds = getBreeds()
.then(response => {
if (response.data.message) {
console.log(`Got ${Object.entries(response.data.message).length} breeds`);
}
})
.catch(error => {
console.log(error);
});
};

countBreeds();

Adding Parameters to GET Requests

Sometimes, you may need to include parameters in your GET requests. Axios provides two ways to achieve this. You can either append the parameters to the URL directly or use the params property in the request options:

1
axios.get('https://site.com/?name=Flavio');
1
2
3
4
5
axios.get('https://site.com/', {
params: {
name: 'Flavio'
}
});

Making POST Requests

Performing a POST request with Axios is similar to making a GET request. Instead of axios.get, you use axios.post. The POST parameters can be provided as an object in the second argument:

1
axios.post('https://site.com/');
1
2
3
axios.post('https://site.com/', {
name: 'Flavio'
});

Using Axios for HTTP requests offers numerous advantages over the native Fetch API, including support for older browsers, request aborting, response timeouts, CSRF protection, upload progress tracking, automatic JSON data transformation, and compatibility with Node.js.

tags: [“JavaScript”, “Axios”, “HTTP requests”, “Node.js”, “XHR”, “Fetch API”, “CORS”]