Open In App

How to correctly use axios params with arrays in JavaScript ?

Last Updated : 22 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

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

Using the map method

  • In this, you need to manually create a URL or query string of the API to make a HTTP request.
  • However you can customize your most complicated URL string more easily with this method but it is not convenient to use such practices.

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];
  
// Manually create the URL string
const URLString = arr.map((value, index) => `arr[${index}]=${value}`).join('&');
  
// HTTP GET request to fetch data using Axios
axios.get(`https://example.com/api/data?${URLString}`)
    .then(result => {
        // Handle the response
        console.log(result.data);
    })
    .catch(error => {
        // Handle errors
        console.error(error);
    });


Output:

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads