DEV Community

Cover image for 🚀 Mastering Axios: Simplifying HTTP Requests
Ruturaj Jadhav
Ruturaj Jadhav

Posted on

🚀 Mastering Axios: Simplifying HTTP Requests

What is Axios?

Axios is a popular JavaScript library for making HTTP requests. It provides a simple API for handling GET, POST, PUT, DELETE, and other HTTP methods with ease.

Why Use Axios?

✅ Supports Promises & Async/Await

✅ Automatic JSON Data Handling

✅ Error Handling Made Easy

✅ Works on Both Browser & Node.js

Installing Axios

npm install axios
Enter fullscreen mode Exit fullscreen mode

Or include it via CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Making Requests with Axios

1️⃣ GET Request

import axios from 'axios';

// Synchronous GET request
const getData = () => {
  axios.get('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => console.log('GET Response:', response.data))
    .catch(error => console.error('GET Error:', error));
};

getData();
Enter fullscreen mode Exit fullscreen mode

2️⃣ POST Request

const postData = () => {
  axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'Axios Guide',
      body: 'This is a simple guide to Axios.',
      userId: 1
    })
    .then(response => console.log('POST Response:', response.data))
    .catch(error => console.error('POST Error:', error));
};

postData();
Enter fullscreen mode Exit fullscreen mode

3️⃣ PUT Request

const putData = () => {
  axios.put('https://jsonplaceholder.typicode.com/posts/1', {
      title: 'Updated Axios Guide',
      body: 'This guide is now updated.',
      userId: 1
    })
    .then(response => console.log('PUT Response:', response.data))
    .catch(error => console.error('PUT Error:', error));
};

putData();
Enter fullscreen mode Exit fullscreen mode

4️⃣ DELETE Request

const deleteData = () => {
  axios.delete('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => console.log('DELETE Response:', response.data))
    .catch(error => console.error('DELETE Error:', error));
};

deleteData();
Enter fullscreen mode Exit fullscreen mode

Why This is Better?

✅ Cleaner syntax compared to Fetch API

✅ Built-in request and response interception

✅ Supports request timeouts and cancellation

✅ Handles all HTTP methods efficiently

Conclusion

Axios makes API requests in JavaScript simpler and more efficient. Whether you're fetching data, updating records, or deleting content, Axios is a must-have for modern web development! 🚀

What Do You Think?

Are you using Axios in your projects? What do you want to learn next? Stay tuned for more! 🚀

📚 Official Documentation

For more details, check out the official Axios documentation: Axios Docs

Top comments (0)