Multiple fields with same key in query params (axios request)?

JavascriptParametersRequestAxios

Javascript Problem Overview


So the backend (not under my control) requires a query string like this:

http://example.com/?foo=5&foo=2&foo=11

But axios uses JS object to send the request params:

axios.get('http://example.com/', { foo: 5 });

And obviously such object can't have multiple fields with the same key.

How can I send a request with multiple fields with same key?

Javascript Solutions


Solution 1 - Javascript

>From the axios documentation on the request config

// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
  ID: 12345
},

To use this in a request, you would do

var request = {
  params: {
    foo: [5, 2, 11]
  }
}
axios.get('http://example.com/', request);

The only issue with using a plain object approach is that array parameters are added as

http://example.com/?foo[]=5&foo[]=2&foo[]=11

To get request without the [] like you want, you can use the URLSearchParams

var params = new URLSearchParams();
params.append("foo", 5);
params.append("foo", 2);
params.append("foo", 11);
var request = {
  params: params
};
axios.get('http://example.com/', request);

This will result in a request as

http://example.com/?foo=5&foo=2&foo=11

Solution 2 - Javascript

In Axios request config, you can override params serialization and then use QS NPM module to serialize array with repeat mode

let params = { foo: [5, 2] }

axios.get('path/to/api/',{params}) // URL : https://path/to/api?foo[]=5&foo[]=2

let myAxios = axios.create({
    paramsSerializer: params => Qs.stringify(params, {arrayFormat: 'repeat'})
})
myAxios.get('path/to/api/',{params}) // URL : https://path/to/api?foo=5&foo=2

Solution 3 - Javascript

Adding more details to @nhydock accepted answer. When you do

var request = {foo: [5, 2, 11] }

axios.get('http://example.com/';, request);

For django application you can receive these as

self.request.query_params.getlist('foo')

also.

Solution 4 - Javascript

The following works fine:

axios.get(`'http://example.com/${foo1}&${foo2}`);

Solution 5 - Javascript

> Disclaimer: I have never used Axios and couldn't find any reference in > the documentation. It is still worth a try. Personally, I would > implement it this way in a library.

It might also be possible to pass arrays as values for the parameter:

axios.get('http://example.com/', { foo: [1, 2, 3, 4, 5] });

Solution 6 - Javascript

If one uses the ready URLSearchParams the handling of multiple parameter values with the same name works with axios as well ... I guess the support for IE came in 2017 ... Works on Safari too, although the links claims that it might not ..

function getUrlParams(){
        // handles multiple param values with the same name
        var url_params = new URLSearchParams(); 
           
        if( window.location.toString().indexOf("?") != -1) {
           window.location.search.split('?')[1].split('#')[0]
              .replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
              var attr = decodeURIComponent(key)
              var val = decodeURIComponent(value)
              url_params.append(attr,val);
           });
        } else {
           // create a default set of params - you might not need this one ...
           url_params = { some_param:"some_value" };
        }
        return url_params ;
     }


     function getBackEndData(url_params, back_end_url){
           // the replace is just a fancy way of converting front-end to back-end call
           return axios.get( back_end_url , { params: url_params } )
           .then(response => {
              return response.data ;
           })
           .catch(function(error) {
              return error.response ; 
              console.log(error.response.data);
           })
     }

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
QuestionMarkus MeskanenView Question on Stackoverflow
Solution 1 - JavascriptnhydockView Answer on Stackoverflow
Solution 2 - JavascriptAshwin KumarView Answer on Stackoverflow
Solution 3 - JavascriptYash AgrawalView Answer on Stackoverflow
Solution 4 - JavascriptMattView Answer on Stackoverflow
Solution 5 - JavascriptAlex PánekView Answer on Stackoverflow
Solution 6 - JavascriptYordan GeorgievView Answer on Stackoverflow