Axios is a Promise-based HTTP client library that can be used in both browser and Node.js environments. It is primarily used to simplify HTTP communication with servers in web applications.
== Overview ==
Axios was first released in 2014 and is an open-source project actively maintained on GitHub. It is based on the XMLHttpRequest interface and provides various features such as JSON data transformation, request/response interception, automatic transformation, and client-side XSRF protection.
== Key Features ==
- Promise API Support: Provides a Promise-based API for handling asynchronous requests.
- Request/Response Interception: Allows intercepting HTTP requests and responses to modify or log them.
- Automatic JSON Transformation: Automatically transforms JSON data received from the server into JavaScript objects.
- Request Cancellation: Provides the ability to cancel requests.
- Concurrent Requests: Can perform multiple requests simultaneously and handle the results.
- CSRF Protection: Supports client-side cross-site request forgery protection.
- Browser/Node.js Compatibility: Usable in both environments.
== Installation ==
=== npm ===
bash
npm install axios
=== yarn ===
bash
yarn add axios
=== CDN ===
html
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
== Basic Usage ==
=== GET Request ===
javascript
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
=== POST Request ===
javascript
axios.post('/user', {
firstName: 'John',
lastName: 'Doe'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
=== Concurrent Requests ===
javascript
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are complete
}));
== Configuration Options ==
Various configuration options can be set for Axios requests:
javascript
{
// Request URL
url: '/user',
// Request method (default: 'get')
method: 'get',
// Base URL
baseURL: 'https://api.example.com',
// Request headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// Request parameters
params: {
ID: 12345
},
// Request data (used for POST, PUT, PATCH requests)
data: {
firstName: 'John'
},
// Request timeout (milliseconds)
timeout: 1000,
// Response type (default: 'json')
responseType: 'json'
}
== Interceptors ==
You can intercept requests or responses before they are handled by then or catch:
javascript
// Request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Handle request error
return Promise.reject(error);
});
// Response interceptor
axios.interceptors.response.use(function (response) {
// Process response data
return response;
}, function (error) {
// Handle response error
return Promise.reject(error);
});
== Error Handling ==
Axios can handle errors in various ways:
javascript
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// Server responded with a status code outside the 2xx range
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// Request was made but no response received
console.log(error.request);
} else {
// Something happened in setting up the request
console.log('Error', error.message);
}
console.log(error.config);
});
== Cancel Tokens ==
Cancel tokens can be used to cancel requests:
javascript
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// Handle error
}
});
// Cancel the request
source.cancel('Operation canceled by the user.');
== Creating Instances ==
You can create Axios instances with custom configurations:
javascript
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
== Browser Support ==
Axios supports the following browsers:
- Chrome
- Firefox
- Safari
- Edge
- Internet Explorer 11
== Related Projects ==
- axios-retry: Automatic retry on request failure
- axios-mock-adapter: Mocking adapter for testing
- vue-axios: Integration with Vue.js
- react-axios: React components
== References ==
[[Category:JavaScript libraries]]
[[Category:HTTP clients]]
[[Category:Open source software]]