Fetching data from APIs is a critical part of modern web development. One of the most popular and powerful libraries for making HTTP requests in JavaScript is Axios.
In this blog post, we'll explore how to use Axios for GET, POST, and other HTTP methods — with clear examples and best practices!
📦 What is Axios?
Axios is a promise-based HTTP client for the browser and Node.js. It simplifies making HTTP requests to external APIs and handles things like JSON parsing, headers, error handling, and more.
✅ Axios supports async/await, request cancellation, interceptors, and automatic transforms.
📥 Installing Axios
If you're using Node.js or React, install Axios using npm or yarn:
npm install axios
or
yarn add axios
If you're using it in the browser directly (CDN):
<span class="na">src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">
🧪 Making API Requests with Axios
✅ 1. Basic GET Request
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response.data); // API data
})
.catch(error => {
console.error('Error fetching data:', error);
});
✅ 2. GET Request using Async/Await
const fetchPosts = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
fetchPosts();
✅ 3. POST Request with Data
const createPost = async () => {
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'New Post',
body: 'This is the body of the new post.',
userId: 1
});
console.log(response.data);
} catch (error) {
console.error('Error creating post:', error);
}
};
createPost();
✅ 4. Sending Custom Headers
axios.get('https://api.example.com/secure-data', {
headers: {
Authorization: 'Bearer your-token-here'
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
🌐 Axios in React Component
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Posts = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => setPosts(response.data))
.catch(error => console.error(error));
}, []);
return (
<div>
<h1>Posts</h1>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
</div>
);
};
export default Posts;
⚙️ Axios Global Configuration
You can set global configs like base URLs, headers, etc.
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.common['Authorization'] = 'Bearer your-token';
Then you can use:
axios.get('/posts'); // No need to repeat the full URL
🚨 Error Handling in Axios
axios.get('/invalid-url')
.then(response => console.log(response))
.catch(error => {
if (error.response) {
console.error('Server responded with:', error.response.status);
} else if (error.request) {
console.error('Request made but no response received.');
} else {
console.error('Something else happened:', error.message);
}
});
🛡️ Interceptors (Advanced)
Axios allows request/response interceptors:
axios.interceptors.request.use(config => {
console.log('Request sent at:', new Date());
return config;
});
🔚 Conclusion
Axios makes it incredibly easy to work with APIs. Whether you're building a Node.js backend or a React frontend, Axios is a developer-friendly tool that helps you:
- Simplify HTTP requests
- Handle errors gracefully
- Customize headers, tokens, and configs
- Make your code cleaner with async/await
✨ Bonus: Axios vs Fetch API
Feature | Axios ✅ | Fetch ❌ |
---|---|---|
Automatically transforms JSON | ✅ | ❌ |
Interceptors support | ✅ | ❌ |
Request cancellation | ✅ | ❌ |
Node.js support out of the box | ✅ | ❌ |
Easy error handling | ✅ | ❌ |
Would you like me to turn this into a blog-ready Markdown file or include images/diagrams?