How do I send a request with superagent that uses the same query parameter
Asked Answered
W

3

8

I am trying to make a request against a php server that is constructing the url like this:

website.com/?q=help&q=moreHelp&q=evenMoreHelp

How do I use superagent to pass the same query with multiple values?

I've tried this:

req.get('website.com').query({q:'help',q:'moreHelp',q:'evenMoreHelp'}).end(...)

But I'm not sure it is actually sending all three 'q' values. What am I supposed to do to make sure they all get sent?

Weaverbird answered 23/6, 2014 at 17:56 Comment(0)
H
8

You definitely will not see all three q values when you pass the query in the manner you are trying, because you are making a JavaScript object there and yes, there will only be one q value:

$ node
> {q:'help',q:'moreHelp',q:'evenMoreHelp'}
{ q: 'evenMoreHelp' }

Superagent allows query strings, as in this example straight from the docs:

request
  .get('/querystring')
  .query('search=Manny&range=1..5')
  .end(function(res){

  });

So if you pass the string 'q=help&q=moreHelp&q=evenMoreHelp' you should be okay. Something like:

req.get('website.com').query('q=help&q=moreHelp&q=evenMoreHelp').end(...)

If this is too ugly, you can try (WARNING: I have not tried this):

req.get('website.com')
 .query({ q: 'help' })
 .query({ q: 'moreHelp' })
 .query({ q: 'evenMoreHelp' })
 .end(...);
Henri answered 23/6, 2014 at 18:3 Comment(2)
Using a query string appears to have solved my issue. Now I just need to convince the php server to give me a proper api so I don't need to pass the same key multiple times.Weaverbird
It is proper and a common practice for an api to take multiple instance of the same key. It's just not so easy to do it with native js objects.Vespine
T
2

As of Superagent 1.5.0 you can pass an array as a property of the query object and it will generate multiple query parameters of the same name:

req.get('website.com').query({foo: ['bar1', 'bar2']})

results in website.com?foo=bar1&foo=bar2

As a side note, if you want Rails parameter[]=value syntax then the following works for me:

req.get('website.com').query({'foo[]': ['bar1', 'bar2']})
Theoretical answered 29/12, 2016 at 8:32 Comment(1)
When I use the .query({foo: []}) syntax with only one element it passes it as a string. I had to use the .query({'foo[]':}) syntax to force it to pass it as an array.Harmony
T
-2

I can confirm that passing the parameters as an array into the query works great, like so:

query: {
      productId,
      orderStatuses: ['FOO', 'BAR', 'OTHER'],
    },
Torre answered 8/4, 2020 at 2:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.