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

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

What is the best way to transform this PHP Object into an array?

I am working with a Javascript array that needs to be passed to a PHP script using Ajax. Inside file.js: var params = {}; params["apples"] = "five"; params["oranges"] = "six"; params["pears"] = "nine"; var ajaxData = {data : params}; fetchData(ajaxData); ...

Looking to include an if/then statement for an item that has been generated within a div?

While I may not be a seasoned programmer, I am facing an issue that requires some problem-solving. Allow me to explain the situation to the best of my ability. Within a "div" element, I have implemented a v-for loop that sets a value in a variable for dis ...

What could be the reason behind my Javascript code returning "object object"?

I am a beginner with jQuery. I attempted to calculate the sum of items from my django views using jQuery. Here's what I have so far: $(document).ready(function() { var sch = $('#sch-books'); var gov = $('#gov-books'); ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Is it advisable to use Angular $resource JSON Callback if it's not functioning correctly?

I am in the process of creating a resource to send data to my controller for an existing API that I need to connect with. Unfortunately, I do not have the ability to make any changes on the backend. Current state of my Resource factory: 'use strict& ...

Is there a way to create a Captcha image from text using JavaScript in an HTML document?

As I work on creating a registration web page, ensuring security is key. That's why I'm looking for a way to generate captcha images for added protection. Any suggestions on how I can transform text into captcha images? ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

Keeping an object in a multidimensional array based on its ID in Angular 4/Ionic 3 without removing it

Exploring a complex data structure: [{ propertyoutsideid: 1, items: [ {itemId: 1, something: 'something'}. {itemId: 2, something: 'something'}. {itemId: 3, something: 'something'}. ] },{ prope ...

What is the best way to retrieve the document DOM object within an EJS template?

I am attempting to display a list of participants when the user clicks on the button. However, every time I try, I encounter an error stating "document is not defined". (Please refrain from suggesting the use of jQuery!). <% var btn = document.getEle ...

Firefox not rendering responsive YouTube embed properly

This method of embedding seems to be functioning well on all browsers except for Firefox; I took advantage of a free trial at crossbrowsertesting.com to verify. I’m not using a direct iFrame embed, and all the solutions I’ve come across are related to ...

Error in Express Session: Property 'signin' is not found in type 'Session & Partial<SessionData>'. Code: 2339

I received the following Error Code: Property 'signin' does not exist on type 'Session & Partial<SessionData>'. (2339) About My Application src/index.ts import "reflect-metadata"; import express = require("expr ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Vue .filter doesn't work with reactive data sources

I'm currently working on a project that involves creating a dynamic shipping estimate in a Shopping Cart. The challenge I face is retrieving shipping methods from an API endpoint and making the data reactive to update in real-time based on the selecte ...

Troubleshooting NPM installation failures with SQLite build

After updating to macOS Mojave and installing the latest versions of node 12.1.0, npm 6.9.0, brew 2.1.1, and Python 2.7.10 on darwin, I encountered an issue while running npm install in a package.json file for a project that includes "sqlite3": "4.0.6". ...

`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove ...

Utilizing an Apollo query that relies on the outcome of a previous query

I’m in the process of constructing an Apollo query within a Vue/Nuxt environment that relies on the outcome of another query. The sessions query requires the presence of person to access this.person.id. How can I make sure that person is available befor ...

javascript for each and every textarea

I am looking to apply my JavaScript code to all the Textarea elements on my page. $_PAGE->addJSOnLoad(" $('.textarea').each(function() { $(this).keyup(function() { var characterCount = $(this).val().length; var mes ...

How can Vue 3 Composition API facilitate the sharing of reactive data among disparate components?

If Component A has a reactive constant that updates based on user actions, how can this data be accessed in another component? For instance: const MyComponent = { import { computed, ref } from "vue"; setup() { name: "Comp ...

Building and deploying Nuxt 3 applications in different environments

Currently, I am in the process of configuring development and production environments within Nuxt 3 for testing purposes. Specifically, I want to utilize a test endpoint if the app URL begins with develop-, staging-, or test-. For instance, when accessing ...