Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use axios params with arrays

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?

like image 258
Zin Kun Avatar asked Apr 20 '18 14:04

Zin Kun


3 Answers

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)
  }
})
like image 63
Nicu Criste Avatar answered Oct 06 '22 19:10

Nicu Criste


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('&')}`);
like image 23
Sergio Loaiza Avatar answered Oct 06 '22 20:10

Sergio Loaiza


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'})
    }
  • Install qs please go to this link
  • Read more about paramsSerializer in axios document
  • Edit format of params: Read more at qs stringifying document
like image 16
Heo Đất Hades Avatar answered Oct 06 '22 19:10

Heo Đất Hades