How to correctly use axios params with arrays

后端 未结 7 481
臣服心动
臣服心动 2021-02-01 14:55

How to add indexes to array in query string?

I tried send data like this:

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


        
相关标签:
7条回答
  • 2021-02-01 14:59

    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)
      }
    })
    
    0 讨论(0)
  • 2021-02-01 14:59

    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
    0 讨论(0)
  • 2021-02-01 15:00

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

    jQuery.param(Object)
    
    0 讨论(0)
  • 2021-02-01 15:08

    This was better for me:

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

    })

    0 讨论(0)
  • 2021-02-01 15:10

    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('&')}`);
    
    0 讨论(0)
  • 2021-02-01 15:10

    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}`)
      }
    })
    
    0 讨论(0)
提交回复
热议问题