You are currently viewing Making HTTP GET Requests with Axios

Making HTTP GET Requests with Axios

When developing web applications, interacting with APIs to fetch data is a fundamental task. HTTP GET requests are the most common method for retrieving data from a server. They are used to request data from a specified resource, such as a database or a file.

Axios, a popular JavaScript library, simplifies the process of making HTTP GET requests by providing a promise-based interface. This makes it easy to handle asynchronous operations in JavaScript. In this comprehensive guide, we’ll explore how to use Axios to make GET requests, handle responses and errors, and configure requests to suit different use cases.

Understanding HTTP GET Requests

An HTTP GET request is a method used to request data from a server at a specified resource. When a GET request is made, the server returns the requested data. This method is considered safe and idempotent, meaning that multiple identical requests should have the same effect as a single request.

Use Cases for GET Requests

GET requests are used in various scenarios, such as:

  • Retrieving a list of items from a database (e.g., a list of users or products).
  • Fetching detailed information about a specific item.
  • Loading content for a webpage or application dynamically.
  • Integrating third-party APIs to fetch data like weather information or stock prices.

Setting Up Axios in Your Project

To start using Axios for making GET requests, you need to set it up in your project. You can install Axios via npm/yarn or include it via a CDN.

Installing Axios via npm/yarn

If you’re using npm or yarn, you can install Axios with a simple command.

Using npm:

npm install axios

Using yarn:

yarn add axios

After installation, you can import Axios in your JavaScript files:

import axios from 'axios';

Setting Up Axios via CDN

If you prefer to include Axios via a Content Delivery Network (CDN), you can add the following script tag to your HTML file:

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

This approach is useful for quick setups or for use in environments where a package manager is not available. When included via CDN, Axios is available globally as axios.

Making Simple GET Requests

Once Axios is set up in your project, making a GET request is straightforward. Here is a basic example.

import axios from 'axios';

// Function to fetch data from an API
const fetchData = async () => {

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

// Call the function to fetch data
fetchData();

If you are using the CDN method, the code will be:

<script>

  // Function to fetch data from an API
  const fetchData = async () => {
  
    try {
	
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      console.log(response.data);
	  
    } catch (error) {
      console.error('Error fetching data:', error);
    }
	
  };

  // Call the function to fetch data
  fetchData();
  
</script>

In this example, we define a function fetchData that makes a GET request to the URL https://jsonplaceholder.typicode.com/posts. The axios.get method initiates a GET request to the specified URL. The await keyword ensures that the function waits for the request to complete before continuing. If the request is successful, the response data is logged to the console. If an error occurs, it is caught by the catch block and logged to the console.

Handling Responses and Errors

When you make a request with Axios, the response object contains several properties, including data, status, statusText, headers, and config. These properties provide detailed information about the response, allowing you to handle it appropriately.

Here’s an example of how to handle responses and errors in Axios:

import axios from 'axios';

// Function to fetch data and handle responses and errors
const fetchData = async () => {

  try {
  
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log('Data:', response.data);
    console.log('Status:', response.status);
	
  } catch (error) {
  
    if (error.response) {
	
      // Server responded with a status other than 2xx
      console.error('Error response data:', error.response.data);
      console.error('Error response status:', error.response.status);
	  
    } else if (error.request) {
	
      // No response received from server
      console.error('Error request:', error.request);
	  
    } else {
	
      // Other errors
      console.error('Error message:', error.message);
	  
    }
	
  }
  
};

// Call the function to fetch data
fetchData();

If you are using the CDN method, the code will be:

<script>

  // Function to fetch data and handle responses and errors
  const fetchData = async () => {
  
    try {
	
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      console.log('Data:', response.data);
      console.log('Status:', response.status);
	  
    } catch (error) {
	
      if (error.response) {
	  
        // Server responded with a status other than 2xx
        console.error('Error response data:', error.response.data);
        console.error('Error response status:', error.response.status);
		
      } else if (error.request) {
	  
        // No response received from server
        console.error('Error request:', error.request);
		
      } else {
	  
        // Other errors
        console.error('Error message:', error.message);
		
      }
	  
    }
	
  };

  // Call the function to fetch data
  fetchData();
  
</script>

In this example, we extend the fetchData function to handle different types of errors. The axios.get method is used to make the request, and the response data and status are logged to the console if successful.

The catch block differentiates between three types of errors:

  • Error response: The server responded with a status code other than 2xx.
  • Error request: The request was made, but no response was received.
  • Other errors: Any other errors that might occur, such as network issues.

By handling these different error scenarios, you can ensure that your application responds appropriately to various error conditions.

Configuring GET Requests

Often, you need to send query parameters along with your GET requests. Axios makes it easy to add these parameters to your request.

import axios from ‘axios’;

// Function to fetch data with query parameters
const fetchData = async () => {

  try {
  
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts', {
      params: {
        userId: 1
      }
    });
	
    console.log('Data:', response.data);
	
  } catch (error) {
    console.error('Error fetching data:', error);
  }
  
};

// Call the function to fetch data
fetchData();

If you are using the CDN method, the code will be:

<script>

  // Function to fetch data with query parameters
  const fetchData = async () => {
  
    try {
	
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts', {
        params: {
          userId: 1
        }
      });
	  
      console.log('Data:', response.data);
	  
    } catch (error) {
      console.error('Error fetching data:', error);
    }
	
  };

  // Call the function to fetch data
  fetchData();
  
</script>

In this example, we define a function fetchData that makes a GET request to the URL https://jsonplaceholder.typicode.com/posts with query parameters. The params option allows us to specify query parameters in a key-value format. The response data is logged to the console if the request is successful, and any errors are caught and logged.

Advanced Usage of GET Requests

Using Axios Interceptors

Interceptors allow you to run your code or modify the request or response before they are handled by then or catch. This is useful for tasks like adding authorization tokens to requests or logging request and response details.

import axios from 'axios';

//Add a request interceptor
axios.interceptors.request.use(

  config => {
    console.log('Request made with ', config);
    config.headers.Authorization = 'Bearer token';
    return config;
  },
  
  error => {
    return Promise.reject(error);
  }
  
);

// Add a response interceptor
axios.interceptors.response.use(

  response => {
    console.log('Response received', response);
    return response;
  },
  
  error => {
    console.log('Error response', error.response);
    return Promise.reject(error);
  }
  
);

// Function to make a request
const fetchData = async () => {

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

// Call the function to fetch data
fetchData();

If you are using the CDN method, the code will be:

<script>

  // Add a request interceptor
  axios.interceptors.request.use(
  
    config => {
      console.log('Request made with ', config);
      config.headers.Authorization = 'Bearer token';
      return config;
    },
	
    error => {
      return Promise.reject(error);
    }
	
  );

  // Add a response interceptor
  axios.interceptors.response.use(
  
    response => {
      console.log('Response received', response);
      return response;
    },
	
    error => {
      console.log('Error response', error.response);
      return Promise.reject(error);
    }
	
  );

  // Function to make a request
  const fetchData = async () => {
  
    try {
	
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      console.log('Data:', response.data);
	  
    } catch (error) {
      console.error('Error fetching data:', error);
    }
	
  };

  // Call the function to fetch data
  fetchData();
  
</script>

In this example, we add request and response interceptors using axios.interceptors.request.use and axios.interceptors.response.use methods. The request interceptor logs the request configuration and adds an authorization header. The response interceptor logs the response details and handles errors. By using interceptors, you can centralize and streamline request and response handling logic, making your code cleaner and more maintainable.

Conclusion

In this article, we explored how to make HTTP GET requests using Axios. We covered the basics of setting up Axios, making simple GET requests, handling responses and errors, configuring GET requests with query parameters, and using interceptors for advanced request handling.

The examples and concepts discussed provide a solid foundation for working with Axios in your projects. However, there is much more to explore. I encourage you to experiment further with Axios, integrating it into your applications to handle API interactions efficiently and effectively.

Leave a Reply