axios tutorial
Introduction to Axios
Axios is a promise-based HTTP client for JavaScript. It works both in the browser and in Node.js. It is simple to use and integrates well with modern JavaScript frameworks.
Setting Up Axios
You can install Axios via npm or include it directly in your HTML file:
npm install axios
Or include via CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Making GET and POST Requests with Axios
Example of a GET request:
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Example of a POST request:
a
xios.post('https://api.example.com/data', {
key1: 'value1',
key2: 'value2'
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
Error Handling with Axios
Axios provides an easy way to handle errors with its catch method:
axios.get('https://api.example.com/invalid-endpoint')
.then(response => console.log(response.data))
.catch(error => {
console.error('Error occurred:', error);
});
You can also inspect error.response for server responses:
if (error.response) {
console.log('Server responded with status:', error.response.status);
}
Advanced Axios Features
Explore advanced features such as interceptors, request cancellation, and custom instance creation:
Using interceptors:
axios.interceptors.request.use(config => {
console.log('Request made with:', config);
return config;
}, error => Promise.reject(error));