Axios: Passing Query Parameters in GET/POST Requests

Updated: February 10, 2023 By: Snowball Post a comment

This quick and at-a-glance article shows you how to pass query parameters in a GET or POST request when using Axios, a very popular Javascript HTTP library.

Passing Query Params in a GET Request

Axios syntax for GET is:

axios.get(url: string, config?: AxiosRequestConfig<any> | undefined)

Therefore, you can add your query params object in the second argument, like so:

const res = await axios.get('https://fake-api.kindacode.com/tutorials', {
        params: {
          paramOne: 'one',
          paramTwo: 'two',
          paramThree: 'three',
          foo: 1,
          bar: 2,
        },
      });

It will make a GET request with 5 query params:

https://fake-api.kindacode.com/tutorials?paramOne=one&paramTwo=two&paramThree=three&foo=1&bar=2

Passing Query Params in a POST Request

Axios syntax for POST is:

axios.post(
   url: string, 
   data?: {} | undefined, 
   config?: AxiosRequestConfig<{}> | undefined
)

So that you can send query params in a POST request through the third argument object, like this:

const res = await axios.post(
        'https://fake-api.kindacode.com/tutorials',
        {
          // data to sent to the server - post body
          // it can be an empty object
        },
        {
          // specify query parameters
          params: {
            paramOne: 'one',
            paramTwo: 'two',
            paramThree: 'three',
          },
        }
      );

The code above will post an empty body with 3 query params:

https://fake-api.kindacode.com/tutorials?paramOne=one&paramTwo=two&paramThree=three

Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles