GET Requests with Axios
Jul 20, 2020
The easiest way to make a GET request with Axios is the
axios.get()
function. The first
parameter to axios.get()
is the URL. For example, below is how you make a GET request
to the URL httpbin.org/get?answer=42
:
const axios = require('axios');
const res = await axios.get('https://httpbin.org/get?answer=42');
res.data.args; // { answer: 42 }
The options
Parameter
The 2nd parameter to axios.get()
is the Axios options.
For example, you don't have to serialize the query string ?answer=42
yourself. Axios will serialize
options.params
and add it to the query string for you. The below request is equivalent:
const axios = require('axios');
// Equivalent to `axios.get('https://httpbin.org/get?answer=42')`
const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });
res.data.args; // { answer: 42 }
The options
parameter is also how you set any request headers. For example,
below is how you set the Test-Header
header on a GET request.
const axios = require('axios');
// httpbin.org gives you the headers in the response
// body `res.data`.
// See: https://httpbin.org/#/HTTP_Methods/get_get
const res = await axios.get('https://httpbin.org/get', {
headers: {
'Test-Header': 'test-value'
}
});
res.data.headers['Test-Header']; // "test-value"
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!