When developing an application or website with JavaScript, making HTTP requests to internal or external APIs is a common task. In such scenarios, Axios stands out as one of the most popular libraries to accomplish this task.
Axios is a popular JavaScript library used for making HTTP requests from the browser or Nodejs. It provides a simple API for performing various types of requests, including GET, POST, PUT, DELETE and more.
In this article, we will focus specifically on the Axios GET request and examine its practical examples.
Installing Axios
Before diving into making GET requests with Axios, you need to install the library. Axios can be easily installed via npm (Node Package Manager) by running the following command in your terminal:
npm install axios
Once installed, you can import Axios into your project using the require
or import
statement, depending on your project setup.
const axios = require('axios'); // for CommonJS (Nodejs)
// or
import axios from 'axios'; // for ES6 modules
Making a Basic Axios GET Request
A GET request is used to retrieve data from a source. To make a GET request with Axios, you can use the axios.get()
method. It takes a URL as the first parameter and returns a Promise that resolves to the response data.
Here’s an example of a basic Axios GET request:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
To break down into parts, we make a GET request to the https://api.example.com/data
endpoint. The axios.get()
method returns a Promise thus allowing to use .then()
and .catch()
to handle the success and failure cases, respectively. In the success case, we log the response data to the console and in the failure case, we log the error.
Handling Response Data
Axios GET method resolves a response object. This object contains various properties, such as data
, status
, headers
and more. The most commonly used property is data
. It holds the actual response data returned by the server.
Here’s an example of how you can access different properties of the response object:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data); // response data
console.log(response.status); // response status code
console.log(response.headers); // response headers
console.log(response.config); // request configuration
})
.catch(error => {
console.error(error);
});
data
: This property contains the response data returned by the server. It could be an object, array, string, or any other data type depending on the server’s response.status
: The HTTP status code of the response (e.g., 200 for a successful request, 404 for a not found error, etc.).statusText
: A string containing the status message corresponding to the status code (e.g., “OK” for 200, “Not Found” for 404, etc.).headers
: An object representing the response headers. You can access specific headers using their names as properties of this object (e.g.,response.headers['content-type']
).config
: The original request configuration object that was used to make the request. It contains information such as the request URL, HTTP method, request headers, and other settings.request
: The XMLHttpRequest object or the http.ClientRequest object (in Nodejs) used to make the request. This property is only available in the browser or in Nodejs if using thehttp
module.
Handling Errors
When an error occurs during an Axios request, the catch block will be executed and you will receive an error object that provides information about the error.
axios.get('https://api.example.com/data')
.then(function(response) {
// Success
})
.catch(function(error) {
if (error.response) {
console.log(error.response.data); // Response data
console.log(error.response.status); // Status code
console.log(error.response.statusText);// Status text
console.log(error.response.headers); // Response headers
} else if (error.request) {
console.log(error.request); // Request object
} else {
console.log('Error', error.message); // Error message
}
console.log(error.config); // Request configuration
});
The Axios error object typically has the following properties:
message
: This is the message that describes the error.response
: When the server sends back an error status code (4xx or 5xx), Axios adds the response details to the error object. These details include the status code, response body, and headers.response.status
: This is the specific code that represents the status of the response.response.data
: The data that is returned by the server as the response body.response.headers
: The headers that are included in the response.
Adding Query Parameters
GET requests often include query parameters in the URL to provide additional information to the server. Axios allows you to pass an optional params
object as the second parameter to the axios.get()
method to add query parameters.
Here’s an example:
axios.get('https://api.example.com/data', {
params: {
limit: 10,
sortBy: 'date',
// ...
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
In the above example, we pass a params
object with key-value pairs to the axios.get()
method. The resulting URL will include the query parameters like https://api.example.com/data?limit=10&sortBy=date
.
Setting Headers
To set headers in an Axios GET request, you can pass an optional configuration object as the second parameter to the axios.get()
function. Within the configuration object, you can specify the headers using the headers
property.
Here’s an example:
axios.get(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
// Add any other headers you need
}
})
.then(response => {
// Handle the response
console.log(response.data);
})
.catch(error => {
// Handle the error
console.error(error);
});
The headers
object contains the headers such as the Content-Type
and Authorization
headers. You can add any other headers you require by adding them to the headers
object.
Making Concurrent Requests
Concurrent requests involve sending multiple API requests simultaneously, which can significantly reduce the overall time required to fetch data. Axios allows us to achieve this by utilizing the axios.all()
and axios.spread()
methods.
Using axios.all()
and axios.spread()
The axios.all()
function takes an array of Axios requests and returns a single promise that resolves when all the requests are complete. The axios.spread()
function is then used to spread the array of responses from axios.all()
into separate arguments.
Here’s a basic example:
const axios = require('axios');
const request1 = axios.get('https://api.example.com/data1');
const request2 = axios.get('https://api.example.com/data2');
axios.all([request1, request2])
.then(axios.spread((response1, response2) => {
// Handle response1.data and response2.data here
}))
.catch(error => {
console.error('Error:', error);
});
In this example, axios.all()
waits for both request1
and request2
to complete, and the responses are then spread into the axios.spread()
function for handling.
Conclusion
Axios is a powerful and easy-to-use library for making HTTP requests in JavaScript while dealing with APIs or external sources. In this article, we explored how to use Axios GET requests to retrieve data from a server, with examples of handling response and error data and adding query parameters and headers to the request.
Thank you for reading.