GET Request Query Params with Axios

Jul 25, 2020

The easiest way to make a GET request with Axios is the axios.get() function. The 2nd parameter to axios.get() is the Axios options: Axios will serialize options.params and add it to the query string for you as shown below.

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 }

You can set options.params to a POJO as shown above, or to an instance of the JavaScript's built-in URLSearchParams class.

const params = new URLSearchParams([['answer', 42]]);

const res = await axios.get('https://httpbin.org/get', { params });
res.data.args; // { answer: 42 }

Customizing Serialization

Axios's built-in query string serializer respects the toJSON() function, so it automatically serializes built-in custom JSON serialization, like Moment objects or Mongoose documents.

const moment = require('moment');

const params = {
  answer: { toJSON: () => 42 },
  time: moment('2016-06-01')
};

const res = await axios.get('https://httpbin.org/get', { params });
res.data.args; // { answer: 42, time: "\"2016-06-01T04:00:00.000Z\"" }

However, if you need more flexibility in how Axios serializes query strings, Axios supports a paramsSerializer option that lets you overwrite the function Axios to serialize.

const params = { answer: 42 };

const res = await axios.get('https://httpbin.org/get', {
  params,
  paramsSerializer: function paramsSerializer(params) {
    // "Hide" the `answer` param
    return Object.entries(Object.assign({}, params,  { answer: 'HIDDEN' })).
      map(([key, value]) => `${key}=${value}`).
      join('&');
  }
});
res.data.args; // { answer: 'HIDDEN' }

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials