1

I'm querying a REST API using vue-resource's $http.get via:

this.$http.get('/api', {
    params: {
        id: [1,2,3],
    },
});

and this produces the query

/api?id[]=1&id[]=2&id[]=3

But my endpoint expects

/api?id=1&id=2&id=3

Is there a way to tell vue-resource to encode multiple parameters like this?

I'd like to avoid constructing my own query string, but that's the alternative I can come up with.

sshine
  • 15,635
  • 1
  • 41
  • 66
  • There is a confusion for me. if your endpoint route is '/api' then the params will automatically be passed.If your endpoint is '/api/:id1/:id2/:id3' you should make request like this `this.$http.get(\`/api/${id1}/${id2}/${id3}\`)`. Also having the same variable in query will result in errors. – Roland Oct 22 '18 at 13:58
  • I didn't say `/api/:id1/:id2/:id3`, I said `/api?id=1&id=2&id=3`. Quoting Wikipedia, "[While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field](https://en.wikipedia.org/wiki/Query_string#Web_forms)". I wonder if `vue-resource` can cater to different standards of passing multiple values to the same parameter. `id[]` resembles the way PHP does it. [Mojolicious](https://mojolicious.org/) does it differently. Welcome to the Wild West. :-) – sshine Oct 22 '18 at 14:21
  • You said /api?id=1&id=2&id=3 which will converted to a dynamic route /api/:id1/:id2/:id3. Maybe I am missing something, but I am trying to help you – Roland Oct 22 '18 at 14:41
  • I'm not sure where this conversion to a dynamic route comes in. Maybe you're thinking of the behavior of another back-end web-framework than the one I'm working with? – sshine Oct 22 '18 at 15:10

1 Answers1

3

Looking by internal implementation of query params serialize function of vue-resource, I can say - no, there is no way to customize query params serialize function in vue-resource.

There is no standard way to pass a collection of values via query string, so format is more framework specific. And while both vue-resource and axios by default use brackets format to serialize arrays, the second one allows to configure custom query serialize function via paramsSerializer option.

Guess, the main reason that there is no standard, is because it is quite easy to create custom function on front-end to serialize query params.

You can use qs.js library to solve your issue

qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false });

Or here is an example of custom function from another answer, but modified to your request:

JSFiddle

aBiscuit
  • 4,414
  • 1
  • 17
  • 28
  • Thanks for the recommendations! I'll consider Axios (which I encountered earlier today), qs.js and simply building my own query string formatter. – sshine Oct 22 '18 at 15:08