W3jar
252 words
1 minutes

How To Send Query Parameters With Axios

When using Axios to send HTTP requests, you can include query parameters in the request URL by specifying them in the params option of the Axios configuration object. Here’s a step-by-step guide on how to do this:

Sending Query Parameters with Axios#

  1. Install Axios (if you haven’t already):

    npm install axios
    
  2. Import Axios into your JavaScript file:

    const axios = require("axios");
    

    or, if you’re using ES modules:

    import axios from "axios";
    
  3. Send a GET Request with Query Parameters:

    When making a GET request, you can include query parameters by using the params option. Here’s an example:

    axios
        .get("https://api.example.com/data", {
            params: {
                param1: "value1",
                param2: "value2",
            },
        })
        .then((response) => {
            console.log(response.data);
        })
        .catch((error) => {
            console.error("Error:", error);
        });
    

    In this example:

    • https://api.example.com/data is the base URL.
    • params is an object where each key-value pair represents a query parameter.
  4. Send a POST Request with Query Parameters:

    Although POST requests typically include parameters in the request body, you can still send query parameters in the URL:

    axios
        .post(
            "https://api.example.com/data",
            {
                // Request body
                key: "value",
            },
            {
                params: {
                    param1: "value1",
                    param2: "value2",
                },
            }
        )
        .then((response) => {
            console.log(response.data);
        })
        .catch((error) => {
            console.error("Error:", error);
        });
    

    In this example:

    • The request body is specified as the second argument to axios.post().
    • The params object is passed as the third argument to axios.post().

Summary#

  • Use the params option to include query parameters in your request.
  • For GET requests, include the params in the configuration object.
  • For POST requests, include the params in the configuration object as well, but the request body is specified separately.

This way, Axios handles the encoding and appending of query parameters to the URL automatically.