How to specify array type request parameter with Axios


This post is written 14 months ago. Probably the information might be out of date.

I wanted to send a request to a path such as

example.com/search?key=a&key=b&key=c

Before axios v1.0.0

Before axios v1.0.0, The qs module was used to parse query strings

var qs = require('qs');

axios.get('/search', {
    params: {'key': ['a', 'b']}
    paramsSerializer: function(params) {
       return qs.stringify(params, {arrayFormat: 'repeat'})
    },
})
copied!

axios version 1.3.6 (Version I tried)

Since axios v1.0.0 onwards, array parsing is supported and the qs module is no longer required.

Specify SerializerOptions indexes: null for the paramsSerializer property of AxiosRequestConfig. The paramSerializer is a property for serialising query parameters.

axios.get('/search', {
    params: {'key': ['a', 'b']}
    paramsSerializer: { indexes: null }
})
copied!

Whe have following SerializerOptions

If indexes = true is specified, the requested URL parameter will be like arr[0]=1&arr[1]=2. If indexes = false is specified, the requested URL parameter will be bracket-only URL without subscripts, such as arr[]=1&arr[]=2. This is the default behaviour. If indexes = null is specified, the requested URL parameter will be such as arr=1&arr=2.

buy me a coffee