Axios Overview
What is Axios?
Axios is a Promise-based HTTP client for browsers and Node.js environments. Created by Matt Zabriskie, it aims to provide a modern, feature-rich alternative for handling cross-platform HTTP requests. Widely adopted in the Vue.js community, Axios is a preferred HTTP client across various frameworks and libraries.
Advantages of Axios Over Other HTTP Libraries:
- Promise Support: Built on Promises, Axios simplifies asynchronous request management and chaining.
- Cross-Platform: Seamlessly operates in both browser and Node.js environments without code changes.
- Interceptors: Allows adding request and response interceptors for tasks like setting universal headers, error handling, or authentication.
- Automatic JSON Parsing: Automatically parses JSON responses, eliminating extra steps.
- Request Cancellation: Supports canceling ongoing requests, useful for scenarios where requests need to be interrupted based on user actions or state changes.
- Data Transformation: Enables transforming request and response data before sending or after receiving.
- Elegant Error Handling: Provides a unified error handling mechanism to capture all types of network errors.
Installing Axios:
To install Axios in a project, use npm or Yarn. For Node.js projects, run:
npm install axios
# or
yarn add axiosIn browser environments, include Axios via CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>Basic Usage Example:
axios.get('https://api.example.com/data')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});
// For a POST request:
axios.post('https://api.example.com/data', {
key: 'value'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error(error);
});Axios Basic Usage
Making a GET Request
GET requests are typically used to retrieve resources. Axios’s get method makes this straightforward.
axios.get('https://api.example.com/data')
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle errors
console.error(error);
});Making a POST Request
POST requests are used to submit data to a server. The post method facilitates this.
axios.post('https://api.example.com/data', {
key: 'value'
})
.then(response => {
// Handle successful response
console.log(response);
})
.catch(error => {
// Handle errors
console.error(error);
});Using async/await for Asynchronous Requests
The async/await syntax makes asynchronous code resemble synchronous code, improving readability.
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();Error Handling and Response Status Codes
Axios converts HTTP errors into Rejection objects containing a response object with status codes and other details.
axios.get('https://api.example.com/data')
.then(response => {
if (response.status === 200) {
console.log(response.data);
} else {
console.error('Unexpected status code:', response.status);
}
})
.catch(error => {
if (error.response) {
// Request was made, but server responded with a non-2xx status
console.error('Server responded with a status of:', error.response.status);
} else if (error.request) {
// Request was made, but no response received
console.error('No response received:', error.request);
} else {
// Error occurred during request setup
console.error('Error setting up the request:', error.message);
}
console.error('Error config:', error.config);
});Code Analysis
Importing Axios: In your JavaScript file, import the Axios module.
import axios from 'axios';Alternatively, use a CDN for browser environments.
Configuring Requests: Axios allows passing configuration options like timeouts and headers.
axios({
method: 'post',
url: 'https://api.example.com/data',
data: {
key: 'value'
},
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer your-token-here'
},
timeout: 5000
})
.then(response => {
// Handle successful response
})
.catch(error => {
// Handle errors
});Handling Responses: Successful responses include properties like data, status, headers, and config, which can be used as needed.
Error Handling: Errors encompass network issues, server errors, and configuration mistakes. Checking error.response, error.request, and error.message provides detailed error information.
Basic Use Case
const axios = require('axios');
// Request a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// Handle success
console.log(response);
})
.catch(function (error) {
// Handle error
console.log(error);
})
.finally(function () {
// Always executed
});
// Alternatively, the same request can be made as follows
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// Always executed
});
// Using async/await
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}



