Utilizing Axios to pass multiple values through a parameter as a comma-separated list

Desired query string format:

http://fqdn/page?categoryID=1&categoryID=2

Axios get request function:

requestCategories () {
  return axios.get(globalConfig.CATS_URL, {
    params: {
      ...(this.category ? { categoryId: this.category } : {})
    }
  })
    .then((resp) => {
      // console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
}

The function works correctly with single values for parameters, but encounters an issue when trying to pass multiple values. Attempted to use an array:

...(this.category ? { categoryId: [1, 2] } : {})

However, the resulting query string is:

http://fqdn/page?categoryID[]=1&categoryID[]=2

Unfortunately, this method does not work as expected. Referenced a related issue on Stack Overflow at: Passing an object with a parameter with multiple values as a query string in a GET using axios

Unable to determine the solution from the provided information.

Answer №1

If you want to customize the serialization of parameters in an Axios request, you can leverage the paramsSerializer option.

An alternative approach is to use the URLSearchParams class which serializes array data as expected:

const searchParams = new URLSearchParams();
searchParams.append('foo', 1);
searchParams.append('foo', 2);
console.log(searchParams.toString()); // foo=1&foo=2

You can incorporate this class within the paramsSerializer function like so:

// my-axios.js
export default axios.create({
  paramsSerializer(params) {
    const searchParams = new URLSearchParams();
    for (const key of Object.keys(params)) {
      const param = params[key];
      if (Array.isArray(param)) {
        for (const p of param) {
          searchParams.append(key, p);
        }
      } else {
        searchParams.append(key, param);
      }
    }
    return searchParams.toString();
  }
});

// Foo.vue
import axios from './my-axios.js';

export default {
  methods: {
    async send() {
      const { data } = await axios({
        url: '//httpbin.org/get',
        params: {
          categoryId: [1, 2, 3]
        }
      });

      // ...
    }
  }
}

Check out the live demo for a hands-on example!

Answer №2

It seems like the issue you are facing is not related to axios, but rather depends on whether your backend service can interpret query parameters in a specific format (which may be framework dependent). It appears that the problem arises when queryParams are sent in the following fashion:

?categoryID[]=1&categoryID[]=2

The backend service expects the queryParams to be formatted like this:

?categoryID = 1,2

To resolve this issue, you can transform the array into a string before passing it as params in axios. Simply update the following section of your code and the problem should be fixed.

...(this.category ? { categoryId: this.category.join(',') } : {})

For more information, refer to the discussion in the following thread:

How to pass an array within a query string?

Answer №3

If you're seeking a way to generate comma-separated values in your URL parameters, like this:

?size=4&sort=modifiedOn,name

Here's how you can do it:

const http = axios.create({

  paramsSerializer: params => new URLSearchParams(params).toString()

})

http.get('/users', {
  params: {
    size: 4,
    sort: ['modifiedOn', 'name']
  }
})

This will give you a serialized query string as follows:

?size=4&sort=modifiedOn%2Cname

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vite failing to recognize updates in Vue/Pug files

It seems that Vite is not able to detect changes in PUG files that are referenced by other PUG files. For instance: div include ./pug/index-2.pug The index-2.pug file is located alongside index.pug, but Vite only recognizes changes in the parent file ...

Displaying images dynamically in Angular using ng-repeat with URL strings

I'm working on a project where I need to dynamically call pictures inside an ng-repeat loop. Initially, I tried adding a key/value pair of 'img' to the JSON object I'm fetching and then dropping it inside the URL. However, this approach ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

What is the current state of Javascript in versions 3.4 and 3.5 of ANTL

Can someone provide information on the current status of the JavaScript target in ANTLR 3.4 or 3.5? I've searched online for answers but haven't found anything conclusive. While I know it was fixed in v3.3 after being broken in v3.2, there is no ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

Verifying if a dropdown option has been chosen through validation in JavaScript

Currently, I am working on implementing a validation block in my JavaScript code to ensure that users have selected a value before proceeding. If a value is not selected, I want to display a pop-up message prompting them to do so. function validate(form) ...

Swap out a module with a different one in a node.js environment

In the scenario where a node.js application consists of numerous files referencing a particular module (like underscore), and there is a need to replace that module with another (such as lodash), the typical approach involves globally replacing the names a ...

Retrieve the ActiveTabIndex value from an Ajax TabContainer using Javascript

Is there a way to retrieve the ActiveTabIndex from TabContainer when a tab is selected by the user? I've attempted the following approach without success. <script type="text/javascript"> function GetActiveTabIndex() { var tc = docum ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

Ways to modify the color of a container's border by interacting with radio buttons through JavaScript

I'm currently facing a challenge with creating a settings dropdown menu that allows users to select different themes. Each theme is supposed to modify the background color and border color, but I have successfully implemented only the background color ...

What are the steps to create a one-way binding between multiple input fields and a master input in Vue3?

In my scenario, there exists a primary HTML <input> element: <template> <input id="tax_master" max="100" min="0" type="number" v-model="taxDefault" /> </template ...

Trouble arises when attempting to parse multiple objects from a JSON file using JavaScript

Encountering JSON parsing issues with multiple JSON objects. JSON data is essential for JavaScript functionality. { "name": "Sara", "age": 23, "gender": "Female", "department": & ...

Issues with external javascript link functionality

I'm having trouble connecting my external JavaScript file to my HTML code. I'm attempting to concatenate two strings using an input function and then display the new string in the empty text field. What could be causing this issue? Appreciate an ...

How can we showcase the data within this loop on the user interface in React JS?

I'm currently working with React JS and I have a question regarding how to display data from a loop in the UI. The code snippet below shows the data being logged to the console, but I want to show it on the actual user interface. Could you please guid ...

Creating a unique input box using CSS and HTML

Could someone help me achieve an input box like the one shown in the image below? https://i.stack.imgur.com/XtVNj.png Since I am new to CSS, I am not sure how to put text inside the border of an input box. Should I style the input directly or create a di ...

Invoke a router inside Node.js once a route has been triggered

I am working with ExpressJS and integrating the Auth0 API for authentication, along with ReactJS on the client side. Due to some limitations of the Auth0 API that I discussed with their team, I have implemented a workaround where I send updated user detail ...

Update the display using a button without the need to refresh the entire webpage

I am currently working on a website project that requires randomized output. I have successfully implemented a solution using Javascript, but the output only changes when the page is reloaded. Is there a way to update the output without refreshing the en ...