Back

How to Make GET Requests with Axios: A Beginner's Guide

How to Make GET Requests with Axios: A Beginner's Guide

When building web apps, fetching data from an API is a common task. JavaScript developers often start with the built-in fetch() method but soon run into issues—such as manually parsing JSON responses and cumbersome error handling. Axios simplifies making HTTP requests, especially GET requests, by offering automatic JSON parsing, better error handling, and easier request customization.

Key Takeaways

  • Axios is a promise-based HTTP client for browsers and Node.js.
  • It automatically handles JSON parsing and simplifies error handling.
  • You can easily set query parameters, headers, and use async/await with Axios.
  • Axios simplifies managing multiple simultaneous GET requests.

What is Axios?

Axios is a popular JavaScript library for making HTTP requests in browsers and Node.js. Unlike the built-in fetch(), Axios automatically parses JSON responses, treats HTTP errors consistently, and supports convenient request features like cancellation and timeouts.

Installing Axios

You can install Axios using npm, Yarn, or include it via CDN:

npm

npm install axios

Yarn

yarn add axios

CDN

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

Import Axios into your project:

import axios from 'axios';
// or
const axios = require('axios');

Making a Basic GET Request

Here’s how you can easily make a basic GET request:

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Axios handles fetching and parsing JSON responses automatically.

Handling Response Data

With Axios, you don’t need extra parsing steps. The returned response contains a data property, already in JavaScript object format:

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(res => {
    console.log(res.data.title);  // Prints the title from the response
  });

Error Handling in Axios GET Requests

Axios handles errors intuitively, catching both HTTP and network issues. Here’s how you can manage these errors clearly:

axios.get('https://jsonplaceholder.typicode.com/invalid-url')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('HTTP error:', error.response.status);
    } else if (error.request) {
      console.error('No response:', error.request);
    } else {
      console.error('Request setup error:', error.message);
    }
  });

Using Query Parameters in Axios GET Requests

Sending query parameters with Axios is easy:

axios.get('https://jsonplaceholder.typicode.com/posts', {
  params: { userId: 1 }
})
.then(response => {
  console.log(response.data);
});

Axios automatically formats these parameters into a query string.

Using Async/Await with Axios

Async/Await syntax makes Axios requests more readable:

async function fetchPosts() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log(response.data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchPosts();

This makes your code simpler and cleaner.

Setting Headers in Axios GET Requests

You can set headers (like authentication tokens) easily:

axios.get('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer YOUR_API_TOKEN'
  }
})
.then(response => {
  console.log(response.data);
});

This lets you include custom headers effortlessly.

Making Multiple GET Requests with Axios

If you need multiple requests at the same time, Axios simplifies it:

const request1 = axios.get('https://jsonplaceholder.typicode.com/posts');
const request2 = axios.get('https://jsonplaceholder.typicode.com/users');

axios.all([request1, request2])
  .then(([posts, users]) => {
    console.log('Posts:', posts.data);
    console.log('Users:', users.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Axios’s handling of simultaneous requests keeps your code efficient.

Conclusion

Axios simplifies HTTP GET requests in JavaScript, eliminating tedious tasks like JSON parsing and complicated error handling. Whether you’re sending simple requests, using query parameters, custom headers, or making multiple concurrent requests, Axios helps you write cleaner, more maintainable code.

FAQs

Yes, Axios works seamlessly in both Node.js and browser environments.

Axios provides automatic JSON parsing, better error handling, and additional features like request cancellation, while Fetch is minimalistic and built into browsers.

Yes, Axios supports POST, PUT, DELETE, and all standard HTTP methods.

Listen to your bugs 🧘, with OpenReplay

See how users use your app and resolve issues fast.
Loved by thousands of developers