2

Expected query string:

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

Axios get request:

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

As you can see, it works perfectly with just 1 value for 1 parameter, but if i wanted to make multiple values - it doesn't work, i've tried to use an array:

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

But it returns this way:

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

So it just not working. Had a look at this issue: Passing an object with a parameter with multiple values as a query string in a GET using axios

But can't figure out, how he solved this problem.

Alexander Kim
  • 17,304
  • 23
  • 100
  • 157

3 Answers3

6

You can use Axios's paramsSerializer to customize the serialization of parameters in the request.

Note that URLSearchParams serializes array data the way you're expecting:

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

So you could use that class in paramsSerializer as follows:

// 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]
        }
      });

      // ...
    }
  }
}

demo

tony19
  • 125,647
  • 18
  • 229
  • 307
  • Thanks, what for is `async` / `await` here? – Alexander Kim Sep 25 '18 at 02:17
  • [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) is an ES2017 feature. – tony19 Sep 25 '18 at 02:19
  • If ES2017 is not available in your project, you can use the ES2016-equivalent code: `send() { axios(...).then(response => { const data = response.data; }); }` – tony19 Sep 25 '18 at 02:22
3

This is not an axios related issue. It depends on whether your backend service is able to understand query params in this fashion(seems to be framework dependent). From your question, I think it is not working when queryParams like following are sent

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

and it expects

?categoryID = 1,2

What you can do is transform array to such string before passing it to params in axios. Update the following piece in your code and it should solve your problem.

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

Take a look at following thread

How to pass an array within a query string?

Shubham Gupta
  • 2,596
  • 1
  • 8
  • 19
0

If you are here looking for how to achieve comma separated values like this:

?size=4&sort=modifiedOn,name

Do this:

const http = axios.create({

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

})

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

Results in serialised query sting:

?size=4&sort=modifiedOn%2Cname

Marc
  • 5,109
  • 2
  • 32
  • 41