How to make an Axios GET request

Axios is a Promise-based HTTP client for JavaScript that can be used in front-end applications and Node.js backends.

What is a GET request

A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios.get().

The get() method requires two parameters to be supplied to it. First, it needs the URI of the service endpoint. Second, it should be passed an object that contains the properties we want to send to our server.

Passing a data object as a parameter to the post method is optional; therefore, ​the post method is very​ similar to the get method.

svg viewer

Code

Axios is a promise-based library. However, we can use async/await to wait for the response from the server. The following code demonstrates this:

import axios from 'axios';
const res = await axios.get(`some-url/todos`);
console.log(res)

Users can also pass additional parameters into the GET request. The promise-based version of this is:

import axios from 'axios';
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })

Copyright ©2024 Educative, Inc. All rights reserved