Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 549
Nathaniel Huff Avatar asked Jun 23 '14 17:06

Nathaniel Huff


People also ask

Can we send query parameters in PUT request?

Is it OK to use query parameters in a PUT request? Absolutely. Query parameters are just another piece of the resource identifier.

What are query strings and how are they used to create parameters for APIs?

A query parameter is a set of parameters appended to the end of a URL. They're URL extensions that let you define customized content or actions based on the information you're passing. A query string, part of a URL, contains data provided to a web-based application and/or a back-end repository.


2 Answers

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(...);
like image 96
Ray Toal Avatar answered Sep 22 '22 14:09

Ray Toal


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']})
like image 32
William Myers Avatar answered Sep 24 '22 14:09

William Myers