What is Axios?
Axios is a popular JavaScript library used to make HTTP requests (GET, POST, PUT, DELETE) from:
- Browser (frontend apps)
- Node.js (backend apps)
Axios is similar to fetch()
but easier to use because:
- It automatically converts responses to JSON.
- It supports request/response interceptors.
- It has better error handling.
Example 1: GET Request
axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log("Error:", error);
});
Output:
{
"userId": 1,
"id": 1,
"title": "Sample title",
"body": "Sample body text..."
}
Example 2: POST Request
axios.post("https://jsonplaceholder.typicode.com/posts", {
title: "My Post",
body: "Hello, this is a test post!",
userId: 1
})
.then(response => {
console.log("Success:", response.data);
})
.catch(error => {
console.log("Error:", error);
});
Output:
{
"title": "My Post",
"body": "Hello, this is a test post!",
"userId": 1,
"id": 101
}
Example 3: Using Async/Await
async function fetchUser() {
try {
let response = await axios.get("https://jsonplaceholder.typicode.com/users/1");
console.log(response.data);
} catch (error) {
console.log("Error:", error);
}
}
fetchUser();
Output:
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz"
}
Difference: Axios vs Fetch
Feature | Fetch | Axios |
---|---|---|
Built-in? | Yes (in browsers) | No (external library) |
Auto JSON parsing | ❌ No (need .json() ) |
✅ Yes |
Error handling | Limited (network only) | Better (status codes too) |
Older browser support | Partial | Better |
Conclusion
- Axios is a simpler and more powerful alternative to
fetch()
. - It works in both browser and Node.js.
- Best choice for large projects or APIs that need error handling and interceptors.
Top comments (0)