Skip to main content

Axios

Installation

Install the Axios library:

npm install axios

Import

Import Axios into your project:

const axios = require('axios');

GET Request

Fetch data from a URL:

axios.get('https://api.example.com/data')

Handle the response using .then() and .catch():

axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));

POST Request

Send data to a URL:

axios.post('https://api.example.com/data', { key: 'value' })
.then(response => console.log(response.data))
.catch(error => console.error(error));

PUT Request

Update data at a URL:

axios.put('https://api.example.com/data/1', { key: 'newValue' })
.then(response => console.log(response.data))
.catch(error => console.error(error));

DELETE Request

Delete data at a URL:

axios.delete('https://api.example.com/data/1')
.then(response => console.log(response.data))
.catch(error => console.error(error));

Custom Configuration

Set custom headers for a request:

axios.get('https://api.example.com/data', { headers: { 'Authorization': 'Bearer token' } })

Set a custom timeout for a request:

axios.get('https://api.example.com/data', { timeout: 5000 })

Interceptors

Add a request interceptor:

axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer token';
return config;
}, error => Promise.reject(error));

Add a response interceptor:

axios.interceptors.response.use(response => {
console.log('Response:', response);
return response;
}, error => Promise.reject(error));