When sending an axios request in my Koa app, one of my query parameters has brackets as so:
lastTenDays:[now-10d TO now]
.
Here is the request:
const response = await this.axiosInstance.get('/somePath', {
params: {
query: query
offset: 0,
limit: 20,
count: true
}
})
When I print the response.request, I notice there's an axios field _currentUrl
which shows the path of the request. In this case, it looks like this:
https://myBaseUrl.com/somePath?query=lastTenDays:[now-10d+TO+now]&offset=0&limit=20&count=true
Here's what's weird. If I encode my query parameter like this: lastTenDays:%5Bnow-10d+TO+now%5D
, the _currentUrl
doesn't change at all!
It seems that when the brackets aren't encoded, they don't get encoded, and when they are encoded, they are decoded on the request. What's going on? How can I prevent this so I can send the encoded brackets in th request?
Turns out axios does some weird stuff. Checkout their code here https://github.com/axios/axios/blob/master/lib/helpers/buildURL.js#L5, and you can see they have a custom encode function that, among other things, unencodes brackets to their plaintext value.
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
This was why whether I passed %5B or '[' to the endpoint, axios always converted it to '['.
The solution:
One can specify a custom param serializer using paramsSerializer
in the request configuration laid out here: https://github.com/axios/axios#request-config.
For example, this could look like:
const querystring = require('querystring')
const response = await this.axiosInstance.get('/somePath', {
params: {
query: query
offset: 0,
limit: 20,
count: true
},
paramsSerializer: querystring.stringify
})