How to use the URLSearchParams In Javascript

  • URLSearchParams() allows you to perform multiple operations of append, delete, or getting and setting the key value in a URL Path.
  • We are using the URLSearchParams() class to serialize the array and pass it in an Axios HTTP request to get the desired response from the API.
  • We can pass the URL Path in the constructor as well or we can leave it empty because URLSearchParams Constructor does not parse full URL strings.

Example: This example shows the implementation of the above-explained approach.

Javascript




const axios = require('axios');
  
// Example array
const arr = [1, 2, 3, 4, 5];
  
// Using URLSearchParams class
const params = new URLSearchParams();
  
arr.forEach((value, index) => {
    params.append(`arr[${index}]`, value);
});
//HTTP GET request to fetch data using Axios
axios.get('https://example.com/api/data', { params })
    .then(result => {
        // Handle the response
        console.log(result.data);
    })
    .catch(error => {
        // Handle errors
        console.error(error.message);
    });


Output:

https://example.com/api/data?arr[0]=1&arr[1]=2&arr[2]=3&arr[3]=4&arr[4]=5

How to correctly use axios params with arrays in JavaScript ?

In this article, we will be going to learn about how to correctly use Axios params with arrays in Javascript. While making HTTP requests in Axios with arrays as parameters in JavaScript, one needs to serialize the array in such a way that the server can understand it easily.

These are the following ways to use Axios params with arrays:

Table of Content

  • Using the URLSearchParams
  • Using the map method

Similar Reads

Using the URLSearchParams

URLSearchParams() allows you to perform multiple operations of append, delete, or getting and setting the key value in a URL Path. We are using the URLSearchParams() class to serialize the array and pass it in an Axios HTTP request to get the desired response from the API. We can pass the URL Path in the constructor as well or we can leave it empty because URLSearchParams Constructor does not parse full URL strings....

Using the map method

...