DEV Community

antony
antony

Posted on

Axios : Simplifying HTTP Requests in JavaScript

Image description

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
Enter fullscreen mode Exit fullscreen mode

Or using yarn:

yarn add axios
Enter fullscreen mode Exit fullscreen mode

In a browser-based project, you can also use a CDN:

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

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);
  });
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

🔹 PUT Request

axios.put('https://example.com/api/posts/1', {
  title: 'Updated Title',
});
Enter fullscreen mode Exit fullscreen mode

🔹 DELETE Request

axios.delete('https://example.com/api/posts/1');
Enter fullscreen mode Exit fullscreen mode

Sending Headers and Auth

axios.get('https://api.example.com/user', {
  headers: {
    Authorization: 'Bearer your-token-here',
  }
});
Enter fullscreen mode Exit fullscreen mode

Creating Axios Instances

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 1000,
  headers: { 'X-Custom-Header': 'foobar' }
});

api.get('/users');
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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)