Onjsdev

Share


Axios Get Request


By onjsdev

Mar 29th, 2024

In Axios, a Get request is easily sent with axios.get method to retrieve data from a target source. Now let's see how to accomplish this.

Installing Axios

Before diving into Axios, you need to ensure it is installed in your project. You can install Axios using npm so olen your terminal and run the following command:

npm install axios

How to Make Axios Get Request

Once Axios is installed, you can start making GET requests. Now, you can use Axios to make a GET request to a specified URL. Here's a basic example:

// Example URL for a GET request
const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';

// Making a GET request using Axios
axios.get(apiUrl)
  .then(response => {
    // Handle the successful response
    console.log('Response:', response.data);
  })
  .catch(error => {
    // Handle errors
    console.error('Error:', error.message);
  });

In this example, we are making a GET request to https://jsonplaceholder.typicode.com/posts/1. The axios.get() function returns a Promise. This why we use .then() for handling successful responses and .catch() for handling errors.

How To Handle Axios Response Data

Axios GET method returns a response object. This object contains various informations, such as data, status and headers. The data holds the actual response data responsed by the server.

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);     // response data
    console.log(response.status);   // response status code
    console.log(response.headers);  // response headers
    console.log(response.config);   // request configuration
  })
  .catch(error => {
    console.error(error);
  });

How To Handle Axios Errors

If an error arises during the Axios GET request, the .catch block will catch and give an error object that provides information about the error.

axios.get('https://api.example.com/data')
  .then(function(response) {
    // Success
  })
  .catch(function(error) {
    if (error.response) {
         console.log('Error', error.message);   // Error message
      console.log(error.response.data);      // Response data
      console.log(error.response.status);    // Status code
      console.log(error.response.statusText);// Status text
      console.log(error.response.headers);   // Response headers
    }
  });

How To Add Query Parameters

GET requests often include query parameters. Axios allows you to add parameters to your requests easily. Here's an example:

const apiUrlWithParams = 'https://jsonplaceholder.typicode.com/posts';
const params = {
  userId: 1,
  _limit: 5,
};

axios.get(apiUrlWithParams, { params })
  .then(response => {
    console.log('Response with Params:', response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

In this example, we are adding query parameters userId and _limit to the GET request.

How to Add Headers

In addition, adding headers to your Axios GET requests is a common requirement, especially when dealing with APIs that require authentication or specific content types.

const axios = require('axios');

// Example URL for a GET request with query parameters
const apiUrlWithParams = 'https://jsonplaceholder.typicode.com/posts';
const params = {
  userId: 1,
  _limit: 5,
};

// Define custom headers
const headers = {
  'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  'Content-Type': 'application/json',
};

// Making a GET request with headers and parameters using Axios
axios.get(apiUrlWithParams, { params, headers })
  .then(response => {
    console.log('Response with Params:', response.data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Conclusion

Axios makes the process of making HTTP requests easy. Whether you are fetching data from an API or interacting with a server, Axios provides clear interface for handling GET requests.

Thank you for reading.