0

I'm using axios.

My app sends query strings along with some GET requests in the typical way:

axios.get({ url: 'whatever.com', params: { key: 'value' } });

However, if a query string value is an array, we run into problems:

// The URL is the escaped stringified array, with brackets: whatever.com?key=%5B%27value1%27%2C%20%27value2%27%5D
axios.get({ url: 'whatever.com', params: { key: ['value1', 'value2'] } });

Instead, I'd want it to look like whatever.com?key=value1,value2.

I could add some custom code to pre-parse array values into a string, but:

  1. I was wondering if axios has tooling for this.
  2. This is risky, because if the values themselves have commas in them, they can't be split.

As a solution for number 2, query params can be serialized in an "exploded" format, eg whatever?key=value1&key=value2, so that the values can be parsed even if they contain commas.

The trouble with this, is I can no longer pass those querystring params in as params to the axios object (because I'd be passing a JS object with duplicate keys), and instead have to append the qs to the url, not using axios's params functionality, and breaking some tooling I have.

Does axios have a built-in way of handling array query params (especially, exploded)? Is there a built-in way of distinguishing between "exploded" and "list" style query params? Any suggestions for how to handle this?

Sasha
  • 6,224
  • 10
  • 55
  • 102
  • 3
    Does this answer your question? [How to correctly use axios params with arrays](https://stackoverflow.com/questions/49944387/how-to-correctly-use-axios-params-with-arrays) – Konrad Aug 30 '22 at 14:11

1 Answers1

0

Regarding the example

whatever.com?key=value1,value2

There is a simple way to reach it

axios.get({ url: 'whatever.com', params: { key: ['value1', 'value2'].join(',') } });