Language: JavaScript
Web
Axios was created to provide a simpler and more consistent API for making HTTP requests in JavaScript compared to the built-in `fetch` API. It supports request and response interception, automatic JSON transformation, and is widely adopted in both front-end and back-end JavaScript projects.
Axios is a promise-based HTTP client for JavaScript that works in both the browser and Node.js. It simplifies making HTTP requests, handling responses, and managing errors.
npm install axiosyarn add axiosAxios allows you to perform HTTP requests using methods such as GET, POST, PUT, DELETE, and more. It returns promises that resolve with response objects containing data, status, headers, and config. Axios also supports request cancellation, interceptors, and timeout configuration.
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => console.log(response.data))
.catch(error => console.error(error));Performs a GET request to the given URL and logs the response data.
import axios from 'axios';
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));Sends a POST request with a JSON payload and logs the returned data.
axios.get('https://jsonplaceholder.typicode.com/posts', {
headers: { 'Authorization': 'Bearer my-token' }
})
.then(response => console.log(response.data));Adds custom headers to a request, useful for authentication or custom API requirements.
axios.interceptors.request.use(config => {
console.log('Request made with config:', config);
return config;
});
axios.interceptors.response.use(response => {
console.log('Response received:', response);
return response;
});Intercepts requests and responses globally for logging, modifying headers, or handling errors.
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token });
source.cancel('Request canceled by user.');Demonstrates canceling a request using Axios CancelToken.
axios.all([
axios.get('/users'),
axios.get('/posts')
]).then(axios.spread((usersRes, postsRes) => {
console.log(usersRes.data, postsRes.data);
}));Performs multiple HTTP requests concurrently and handles the responses together.
Use interceptors for handling authentication, logging, or error processing.
Always catch errors and handle them gracefully.
Use environment variables for base URLs and API tokens.
Leverage request cancellation to avoid race conditions or unnecessary network calls.
Use async/await syntax for cleaner asynchronous code.