Making HTTP Requests with Axios
Aug 24, 2023
Making HTTP Requests with Axios
Axios is a popular JavaScript library that simplifies making HTTP requests from the browser or Node.js. It provides an easy-to-use API for sending GET, POST, PUT, DELETE and other types of HTTP requests and handling responses. Axios supports the Promise API, has request and response interceptors, transforms request and response data, and can automatically convert data to JSON.
The key features and benefits of using Axios for making HTTP requests include:
Simple and intuitive API
Client-side support for protecting against XSRF
Automatic transforms for JSON data
Request and response interceptors
Built-in support for download progress
Cancellation of requests
Works in all modern browsers and Node.js
Installing Axios
To get started, install Axios via npm:
npm install axios
Or include it via a CDN link in your HTML:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Making a GET Request
To make a GET request, use the axios.get()
method and provide the URL:
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
The response object contains the data returned from the API, which is accessed via response.data
.
You can also provide an options object to configure the request:
axios.get('https://api.example.com/data', {
params: {
id: 123
},
headers: {
'Authorization': 'token'
}
})
Making a POST Request
To send data to an API, use the axios.post()
method:
axios.post('https://api.example.com/data', {
name: 'John Smith',
age: 25
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
The second argument is the data object to send in the request body. Axios will automatically serialize this to JSON.
Intercepting Requests
You can intercept and modify requests before they are sent using axios.interceptors.request
:
axios.interceptors.request.use(config => {
// Modify request config
config.headers['Authorization'] = 'token';
return config;
});
Intercepting Responses
Responses can also be intercepted to modify the data or handle errors:
axios.interceptors.response.use(response => {
// Modify response data
response.data = response.data.map(x => x * 2);
return response;
}, error => {
// Handle errors
if (error.response.status === 404) {
// Handle 404 error
}
return Promise.reject(error);
});
Summary
Axios provides a clean, promise-based API for making HTTP requests in JavaScript. With support for request/response interceptors, automatic transforms, and a simple config object, it reduces boilerplate and simplifies common AJAX use cases. Axios' wide browser support and ability to work in Node.js make it a versatile, go-to choice for handling HTTP communication in JavaScript applications.
Let's get scraping 🚀
Ready to start?
Get scraping now with a free account and $25 in free credits when you sign up.