How to Use Axios for API Requests in JavaScript

3>What is Axios?
Axios is a promise-based HTTP client for JavaScript that enables smooth communication between your web application and a backend server. It simplifies the process of making API requests, providing an easy-to-use API and powerful features that make it suitable for both front-end and back-end JavaScript applications.
Setting Up Axios
To start using Axios, you need to install it. If you’re using npm, you can install it by running the following command:
npm install axiosAlternatively, if you want to include it directly in your HTML file, you can link to a CDN:
Making GET Requests
Making GET requests with Axios is straightforward. Here is a basic example:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});In this example, Axios fetches data from a specified URL. The response is handled using .then() for a successful request and .catch() for error handling.
Making POST Requests
To send data to a server, you would typically use a POST request. Here’s how you would do it with Axios:
axios.post('https://api.example.com/data', {
name: 'John Doe',
age: 30
})
.then(response => {
console.log('Data saved:', response.data);
})
.catch(error => {
console.error('Error:', error);
});The second argument to axios.post is the payload (data) that you want to send to the server.
Handling Responses
Axios responses contain several properties. Among the most notable are:
data: The data returned by the server.status: The HTTP status code of the response.statusText: The status text corresponding to the HTTP status code.headers: The headers of the response.config: The config object used to make the request.
Here’s how you can access these properties:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
})
.catch(error => {
console.error('Error:', error);
});Configuring Requests
Axios allows you to configure requests globally or per request. Here’s how to set default configurations:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';You can also configure individual requests:
const config = {
headers: {
'Content-Type': 'application/json',
},
timeout: 1000,
};
axios.post('/data', payload, config)
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});Interceptors
Interceptors are a powerful feature of Axios that allow you to run your code or modify requests before they are sent or responses before they are handled.
Request Interceptor
You can add a request interceptor like this:
axios.interceptors.request.use(config => {
// Do something before request is sent
config.headers['X-Custom-Header'] = 'Custom Value';
return config;
}, error => {
// Handle the error
return Promise.reject(error);
});Response Interceptor
For response interceptors:
axios.interceptors.response.use(response => {
// Any status code within the range of 2xx causes this function to trigger
return response;
}, error => {
// Any status codes outside the range of 2xx causes this function to trigger
return Promise.reject(error);
});Error Handling
Handling errors effectively is crucial in application development. Axios allows you to manage errors in a granular way. You can check for specific status codes or use a generic handler:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// The request was made, but the server responded with a status code
console.error('Response error:', error.response.data);
console.error('Status code:', error.response.status);
} else if (error.request) {
// The request was made but no response was received
console.error('Request error:', error.request);
} else {
// Something else happened while setting up the request
console.error('Error:', error.message);
}
});Canceling Requests
If you need to cancel a request, you can use Axios’s cancel token feature:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('https://api.example.com/data', {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
}).then(response => {
console.log(response.data);
}).catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.error('Error:', thrown);
}
});
// Cancel the request
if (cancel) {
cancel('Operation canceled by the user.');
}Concurrent Requests
You may need to make multiple requests simultaneously. Axios makes this simple with axios.all() and axios.spread():
axios.all([
axios.get('https://api.example.com/data1'),
axios.get('https://api.example.com/data2')
]).then(axios.spread((response1, response2) => {
console.log('Data from first request:', response1.data);
console.log('Data from second request:', response2.data);
})).catch(error => {
console.error('Error in one of the requests:', error);
});Conclusion
Axios is a robust, flexible HTTP client that simplifies the process of making API requests in JavaScript. With features like interceptors, cancellation, and concurrent requests, it can greatly enhance your API interaction experience, whether you are building simple web applications or complex single-page applications. Implementing Axios effectively can lead to more maintainable and scalable code in your JavaScript projects.





