How to correctly use axios params with arrays

JavascriptArraysAxiosHttp Get

Javascript Problem Overview


How to add indexes to array in query string?

I tried send data like this:

axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })

And I got this url:

http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3

So, I should to get this url:

http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3

What I should add in my params options to get this url?

Javascript Solutions


Solution 1 - Javascript

You can use paramsSerializer and serialize parameters with https://www.npmjs.com/package/qs

axios.get('/myController/myAction', {
  params: {
    storeIds: [1,2,3]
  },
  paramsSerializer: params => {
    return qs.stringify(params)
  }
})

Solution 2 - Javascript

Without having to add more libraries and using ES6 you could write:

axios.get(`/myController/myAction?${[1,2,3].map((n, index) => `storeIds[${index}]=${n}`).join('&')}`);

Solution 3 - Javascript

Thanks so much the answer from Nicu Criste, for my case, the API requires params like this:

params: {
  f: {
    key: 'abc',
    categories: ['a','b','c']
   },
  per_page: 10
}

Method is GET and this API requires the format is: API?f[key]=abc&f[categories][]=a&f[categories][]=b... So I assigned the paramsSerializer of axios like this:

config.paramsSerializer = p => {
      return qs.stringify(p, {arrayFormat: 'brackets'})
    }

Solution 4 - Javascript

In my case, I use ES6 array function. array element make querystring use reduce function. Object array also works.

const storeIds = [1,2,3]
axios.get('some url', {
  params: {
    storeIds: storeIds.reduce((f, s) => `${f},${s}`)
  }
})

Solution 5 - Javascript

In my case, I am using someting like this

const params = array.map((v)=>{
            return `p=${v}&`
        })

Only concat params.join('') to the URL where you get data:

`url_to_get?${params.join('')`

In my back-end in ASP.net I receive this

[FromUri] string [] p

Solution 6 - Javascript

I rewrote the existing paramSerializer shipped in axios. The following snippet does the same serialization while putting indices between square brackets. I tried qs but it is not compatible with my python connexion backend (for JSON string parameters).

const rcg = axios.create({
    baseURL: `${url}/api`,
    paramsSerializer: params => {
        const parts = [];

        const encode = val => {
            return encodeURIComponent(val).replace(/%3A/gi, ':')
                .replace(/%24/g, '$')
                .replace(/%2C/gi, ',')
                .replace(/%20/g, '+')
                .replace(/%5B/gi, '[')
                .replace(/%5D/gi, ']');
        }

        const convertPart = (key, val) => {
            if (val instanceof Date)
                val = val.toISOString()
            else if (val instanceof Object)
                val = JSON.stringify(val)

            parts.push(encode(key) + '=' + encode(val));
        }

        Object.entries(params).forEach(([key, val]) => {
            if (val === null || typeof val === 'undefined')
                return

            if (Array.isArray(val))
                val.forEach((v, i) => convertPart(`${key}[${i}]`, v))
            else
                convertPart(key, val)
        })

        return parts.join('&')
    }
});

Solution 7 - Javascript

I got using "paramSerializer" a bit confuse. Before looking for the "right way" to use axios with array querystring on Google, I did following and got working:

var options = {};
var params = {};
for(var x=0;x<Products.length;x++){
   params[`VariableName[${x}]`] = Products[x].Id;
}
options.params = params;

axios.get(`https://someUrl/`, options)...

It is going to create querystring parameters like:

VariableName[0]=XPTO,VariableName[1]=XPTO2

which the most webservers expected as array format

Solution 8 - Javascript

I know that this approach is not very good and I don't know the downsides it may have, but i tried this and it worked:

before making the request, prepare the params:

  let params = '?';

  for (let i = 0; i < YOUR_ARRAY.length; i++) {  // In this case YOUR_ARRAY == [1, 2, 3]
    params += `storeIds=${YOUR_ARRAY[i]}`;  // storeIds is your PARAM_NAME
    if (i !== YOUR_ARRAY.length - 1) params += '&';
  }

And then make the request like so:

axios.get('/myController/myAction' + params)

Solution 9 - Javascript

This answer is inspired by @Nicu Criste's answer.

But might be not related to the posted question.

The following code was used to generate the query params with repetitive keys which had been supplied with an object array.

Note: If you are a developer with bundlephobia, use the following approach with care: as with UrlSearchParams support varies on different browsers and platforms.

const queryParams = [{key1: "value1"}, {key2: "value2"}]

axios.get('/myController/myAction', {
  params: queryParams,
  paramsSerializer: params => {
    return params.map((keyValuePair) => new URLSearchParams(keyValuePair)).join("&")
  }
})

// request -> /myController/myAction?key1=value1&key2=value2

Solution 10 - Javascript

This work it for me:

axios.get("/financeiro/listar",{
        params: {
          periodo: this.filtro.periodo + "",
          mostrarApagados: this.filtro.mostrarApagados,
          mostrarPagos: this.filtro.mostrarPagos,
          categoria: this.filtro.categoria,
          conta: this.filtro.conta
        }
      })

enter image description here

Solution 11 - Javascript

This was better for me:

axios.get('/myController/myAction', {
params: { storeIds: [1,2,3] + ''}

})

Solution 12 - Javascript

In my case, there was already jQuery implemented into my codebase. So I just used the predefined method.

jQuery.param(Object)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZin KunView Question on Stackoverflow
Solution 1 - JavascriptNicu CristeView Answer on Stackoverflow
Solution 2 - JavascriptSergio LoaizaView Answer on Stackoverflow
Solution 3 - JavascriptHeo Đất HadesView Answer on Stackoverflow
Solution 4 - Javascript이한빈View Answer on Stackoverflow
Solution 5 - JavascriptSergio Hidalgo RoblesView Answer on Stackoverflow
Solution 6 - JavascriptAykut KllicView Answer on Stackoverflow
Solution 7 - JavascriptAllan ZeidlerView Answer on Stackoverflow
Solution 8 - JavascriptAli BaghbanView Answer on Stackoverflow
Solution 9 - JavascriptJayanga JayathilakeView Answer on Stackoverflow
Solution 10 - JavascriptRogério VianaView Answer on Stackoverflow
Solution 11 - JavascriptJorgeView Answer on Stackoverflow
Solution 12 - JavascriptBastin RobinView Answer on Stackoverflow