Introduction to Axios
Axios is a powerful HTTP client for making API requests from Node.js and the browser. It is known for its simplicity and ease of use, making it an excellent choice for both beginners and experienced developers. In this guide, we will explore dozens of useful Axios API features with code snippets. By the end, you will also see an example app demonstrating these features.
Basic Usage
The most fundamental method you can use with Axios is the get
method.
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
POST Request
Sending a POST request with Axios is just as simple:
axios.post('/user', {
firstName: 'John',
lastName: 'Doe'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
PUT Request
axios.put('/user/12345', {
firstName: 'John',
lastName: 'Smith'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
DELETE Request
axios.delete('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Instance Creation
You can create an Axios instance with a custom configuration:
const instance = axios.create({
baseURL: 'https://api.example.com'
});
instance.get('/user')
.then(function (response) {
console.log(response);
});
Setting Headers
Setting HTTP headers is straightforward with Axios:
axios.get('/user', {
headers: {
'X-Custom-Header': 'foobar'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Handling Errors
Axios allows you to handle errors in a simple way:
axios.get('/user/12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
});
Interceptors
You can intercept requests or responses before they are handled:
axios.interceptors.request.use(function (config) {
// Do something before the request is sent
return config;
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
// Do something with the response data
return response;
}, function (error) {
return Promise.reject(error);
});
Canceling Requests
Axios provides a way to cancel requests:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user', {
cancelToken: source.token
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.log('Error', thrown.message);
}
});
source.cancel('Operation canceled by the user.');
Example App
Let’s put all the pieces together in a small app that performs CRUD operations.
// Define base URL
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000
});
// Application logic
async function app() {
try {
// CREATE
let response = await api.post('/posts', {
title: 'foo',
body: 'bar',
userId: 1
});
console.log('Created:', response.data);
// READ
response = await api.get('/posts/1');
console.log('Read:', response.data);
// UPDATE
response = await api.put('/posts/1', {
title: 'foo',
body: 'baz',
userId: 1
});
console.log('Updated:', response.data);
// DELETE
response = await api.delete('/posts/1');
console.log('Deleted:', response.status);
} catch (error) {
console.error('Error in app operations:', error);
}
}
// Run the app
app();
This guide should help you get started with Axios for handling HTTP requests in your web applications.
Hash: b45312c3f297dfaa5e2c0bd5760e12c29e9cb7812a74f6afa5d4d44448556236