How To Send Query Parameters With Axios?

Axios is a popular JavaScript library for making HTTP requests, and it provides a convenient way to include query parameters in your requests. In this tutorial, we will explore how to send request query parameters with Axios.

Sending Requests with Query Parameters in Axios

1. Using the “params” Option

Axios provides a straightforward way to send query parameters using the params option. Here’s how to do it:

const axios = require('axios'); // Import Axios

const baseURL = 'https://api.example.com/data'; // The base URL

// Define query parameters
const myParams = {
    category: 'books',
    author: 'John Doe',
    sortBy: 'date',
};

// Send the GET request with the query parameters using the `params` option
axios
    .get(baseURL, { params: myParams })
    .then((response) => {
        console.log(response.data);
    })
    .catch((error) => {
        console.error(error);
    });
# The Request URL will be like this
https://api.example.com/data?category=books&author=John+Doe&sortBy=date

In this code, we pass the params object directly to the Axios request as an option. Axios will automatically create the query string for you and append it to the URL.

2. Using a Query String:

You can send query parameters in the URL by manually constructing the query string. Axios allows you to include query parameters directly in the URL. Here is an example:

const axios = require('axios'); // Import Axios

const baseURL = 'https://api.example.com/data'; // The base URL

// Define query parameters
const params = {
    category: 'books',
    author: 'John Doe',
    sortBy: 'date',
};

// Create the query string from the parameters
const queryString = new URLSearchParams(params).toString();

// Combine the base URL and the query string
const requestURL = `${baseURL}?${queryString}`;

// Send the GET request with the query parameters
axios
    .get(requestURL)
    .then((response) => {
        console.log(response.data);
    })
    .catch((error) => {
        console.error(error);
    });

In this example, we define the query parameters in the params object and use URLSearchParams to create a query string. We then combine the base URL and query string to form the complete request URL.