DEV Community

Dev Cookies
Dev Cookies

Posted on

πŸš€ How to Fetch API Using Axios in JavaScript (With Code Examples)

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

or

yarn add axios
Enter fullscreen mode Exit fullscreen mode

If you're using it in the browser directly (CDN):

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

πŸ§ͺ 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);
  });
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

βš™οΈ 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';
Enter fullscreen mode Exit fullscreen mode

Then you can use:

axios.get('/posts'); // No need to repeat the full URL
Enter fullscreen mode Exit fullscreen mode

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

πŸ›‘οΈ Interceptors (Advanced)

Axios allows request/response interceptors:

axios.interceptors.request.use(config => {
  console.log('Request sent at:', new Date());
  return config;
});
Enter fullscreen mode Exit fullscreen mode

πŸ”š 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?

Top comments (0)