Axios get with param array

13,847

When composing a query string where one field has multiple values (i.e. if it were an array), then there is no standard that says how it must be encoded in the query string, however most web servers accept this syntax:

http://localhost:8081/cidade/?q[]=value1&q[]=value2

which is why axios defaults to it. Check your web server to see if it is reading the parameter as an array correctly.

If you want to force it to be encoded in some other way, just convert the array to a string in whatever format you want and send it as a single value:

this.$axios.get('/cidade/', {
  params: {
    q: JSON.stringify(result)
  }
})
http://localhost:8081/cidade/?q=[value1,value2]

(The [ and ] characters may be percent-encoded.)

In general, this syntax cannot distinguish between the string "[value1,value2]" and the array [value1, value2], so the web server will have to choose one or the other. Again, this is all dependent on your web server.

Share:
13,847

Related videos on Youtube

Fabio Ebner
Author by

Fabio Ebner

Updated on June 04, 2022

Comments

  • Fabio Ebner
    Fabio Ebner almost 2 years

    I create one get request with axios:

    this.$axios.get('/cidade/',{
              params: {
                q: result,
              }
            })
            .then((response) => {
              this.cidades = response.data;
            })
            .catch(function (error) {
              // handle error
              // eslint-disable-next-line
              console.log(error);
            })
            .then(function () {
    
              // always executed
            });
    

    but my result is an array [123asdas1,asdasd2312] and when the axios excute the request he create that url:

    http://localhost:8081/cidade/?q[]=5b9cfd0170607a2e968b0a1e&q[]=5b9cfd0170607a2e968b0a1d
    

    so It's possible to remove the [] from q param? how?

    tks

    • Nate
      Nate over 5 years
      The way it’s doing it is the proper way to send a parameter array in a url. Your server should parse that to a single q param whose value is an array of ["5b9cfd0170607a2e968b0a1e", "5b9cfd010607a2e968b0a1d"]. Is your server not parsing the param that way? Because it should be. If not, then you should try to figure out why that is.
    • andruso
      andruso about 4 years