Comprehensive Guide and API Examples for Mastering Axios
Axios is a popular promise-based HTTP client for JavaScript that can be used in both the browser and Node.js environments. It is designed to make HTTP requests easy and efficient.
Installing Axios
// Using npm
npm install axios
// Using yarn
yarn add axios
Basic Usage
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
GET Request
axios.get('https://api.example.com/data')
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
POST Request
axios.post('https://api.example.com/data', {
firstName: 'John',
lastName: 'Doe'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
PUT Request
axios.put('https://api.example.com/data/1', {
firstName: 'Jane'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
DELETE Request
axios.delete('https://api.example.com/data/1')
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
Custom Headers
axios.get('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token123'
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
Setting Default Config
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token123';
axios.defaults.headers.post['Content-Type'] = 'application/json';
Interceptors
axios.interceptors.request.use(config => {
console.log('Request sent at ' + new Date().toISOString());
return config;
}, error => {
return Promise.reject(error);
});
axios.interceptors.response.use(response => {
console.log('Response received at ' + new Date().toISOString());
return response;
}, error => {
return Promise.reject(error);
});
Handling Errors
axios.get('https://api.example.com/data')
.then(response => {
console.log(response);
})
.catch(error => {
if (error.response) {
console.log('Problem With Response:', error.response.status);
} else if (error.request) {
console.log('Problem With Request:', error.request);
} else {
console.log('Error:', error.message);
}
});
Combining Requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perm) {
console.log('Account:', acct.data);
console.log('Permissions:', perm.data);
}));
Creating an Application
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/posts', async (req, res) => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
res.json(response.data);
} catch (error) {
res.status(500).send(error.message);
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
This guide demonstrated the basics and advanced features of Axios to help you make HTTP requests conveniently. Axios is a versatile and intuitive library that can be easily integrated into your projects.
Hash: b45312c3f297dfaa5e2c0bd5760e12c29e9cb7812a74f6afa5d4d44448556236