![]() |
VOOZH | about |
Axios is a popular open-source JavaScript library used to make HTTP requests from web browsers or Node.js environments. It simplifies the process of sending asynchronous HTTP requests to REST endpoints, handling responses, and performing various network-related tasks.
Built on top of JavaScript’s native XMLHttpRequest and the fetch API,Axios offers a more user-friendly API with features like interceptors, automatic JSON data transformation, error handling, and support for older browsers.
You can install Axios using npm (Node Package Manager) or directly include it in your HTML file.
To install Axios in a Node.js project, run:
npm install axiosFor use in a browser environment, include Axios via a CDN link in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>Using Axios is straightforward and intuitive. Here is a basic example of making a GET request to fetch data from an API.
const axios = require('axios');
// Making a GET request
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
// Making a POST request
axios.post('https://api.example.com/data', {
name: 'John Doe',
age: 30
})
.then(response => {
console.log('Data posted successfully:', response.data);
})
.catch(error => {
console.error('Error posting data:', error);
});
You can set default configuration options for Axios requests. For example:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 5000; // Set a timeout for requests
Interceptors allow you to perform actions or modifications before a request is sent or after a response is received:
// Add a request interceptor
axios.interceptors.request.use(
function (config) {
console.log('Request sent at:', new Date());
return config;
},
function (error) {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
return Promise.reject(error);
}
);
If you need to cancel an ongoing request, you can use the CancelToken feature:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('https://api.example.com/data', { cancelToken: source.token })
.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
source.cancel('Request canceled by the user.');
Axios provides an easy way to handle errors with the catch block:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.error('Error data:', error.response.data);
console.error('Error status:', error.response.status);
console.error('Error headers:', error.response.headers);
} else if (error.request) {
console.error('Request error:', error.request);
} else {
console.error('Error message:', error.message);
}
});
Create a simple HTML file and a JavaScript file.
index.html: The HTML file will include a basic structure with a button to fetch users, a list to display the data, and a form to add a new user.
app.js: The JavaScript file will handle the logic for making HTTP requests using Axios.
Create an index.html file with the following content:
Create an app.js file with the following content: