Whether you're building a weather app, consuming a RESTful API, or submitting form data, making HTTP requests is a fundamental part of modern web development. That's where Axios shines. In this post, we’ll explore what Axios is, why it's useful, and how to get started with it.
What is Axios?
Axios is a promise-based HTTP client for the browser and Node.js. It makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations (Create, Read, Update, Delete).
You can think of Axios as an advanced version of fetch()
, but with a cleaner syntax and additional features.
Installing Axios
bash
npm install axios
Or using yarn:
yarn add axios
In a browser-based project, you can also use a CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Making Your First Request
Here’s a simple GET request to fetch some JSON data:
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Using Async/Await (Modern Approach):
const fetchPosts = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log('Data:', response.data);
} catch (error) {
console.error('Error:', error);
}
};
fetchPosts();
Common HTTP Methods in Axios
🔹 POST Request
axios.post('https://example.com/api/posts', {
title: 'New Post',
body: 'This is the content.',
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
🔹 PUT Request
axios.put('https://example.com/api/posts/1', {
title: 'Updated Title',
});
🔹 DELETE Request
axios.delete('https://example.com/api/posts/1');
Sending Headers and Auth
axios.get('https://api.example.com/user', {
headers: {
Authorization: 'Bearer your-token-here',
}
});
Creating Axios Instances
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' }
});
api.get('/users');
Error Handling Best Practice
try {
const response = await axios.get('/some-endpoint');
} catch (error) {
if (error.response) {
console.error('Server Error:', error.response.status);
} else if (error.request) {
console.error('No Response:', error.request);
} else {
console.error('Error', error.message);
}
}
Final Thoughts
Axios is a powerful, battle-tested HTTP client that simplifies API communication in your JavaScript applications. Whether you're just starting out or building large-scale apps, Axios helps you write cleaner, more reliable code.
Top comments (0)