nestorthecat nestorthecat - 15 days ago 5
Node.js Question

Adjusting the querystring/URL in Node's request module

I am using the npm request module to make a request within an Express.js application to an internal API. I am passing the following options to the

request
function:

requestOptions = {
url : http://whatever.com/locations/
method : "GET",
json : {},
qs : {
lng : longitude,
lat : latitude + '/predictions'
}


The latitude and longitude parameters will change depending on user input and so can not be hard coded.

An example of a URL I wish to make the request to is
http://whatever.com/locations/37.891726,-122.277858/predictions
.

Unfortunately, the result of
request(requestOptions, callback)
is that the request is made to
http://whatever.com/locations/?lng=37.891726&lat=-122.277858%2Fpredictions
.

I know from the documentation that I can adjust the separator from
&
to
,
, and also that the
/
I manually appended to
lat
can be properly sent if I add the attribute
qsStringifyOptions : {encode: false}
to
requestOptions
. But appending
/predictions
manually the way I did feels wrong to begin with, and I still have the difficulty of the remaining format -- namely, removing the
lat=
/
lng=
, the initial ? from the query string.

Is it possible to somehow change the querystring options to suit my needs, or is it possible that the request package is not what I want?

Answer

if http://whatever.com/locations/[lng],[lat]/predictions is what you want then lng & lat are not querystring parameters, but part of the URI path. You can skip the querystring entirely and change your requestOptions to:

requestOptions = {
    url: 'http://whatever.com/locations/' + lng + ',' + lat + '/predictions',
    method: 'GET',
    json: {}
};