在Node的请求模块

时间:2016-11-24 15:20:28

标签: javascript node.js express npm http-get

我正在使用npm请求模块在Express.js应用程序中向内部API发出请求。我将以下选项传递给request函数:

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

纬度和经度参数将根据用户输入而改变,因此无法进行硬编码。

我希望发出请求的网址的示例是http://whatever.com/locations/37.891726,-122.277858/predictions

不幸的是,request(requestOptions, callback)的结果是请求http://whatever.com/locations/?lng=37.891726&lat=-122.277858%2Fpredictions

我从documentation知道我可以将分隔符从&调整为,,并且/我手动附加到lat可以如果我将属性qsStringifyOptions : {encode: false}添加到requestOptions,则会正确发送。但是,按照我的方式手动添加/predictions会让我感到错误,并且我仍然难以使用剩余的格式 - 即删除lat= / lng=,最初的?来自查询字符串。

是否有可能以某种方式更改查询字符串选项以满足我的需要,或者请求包可能不是我想要的?

1 个答案:

答案 0 :(得分:0)

如果http://whatever.com/locations/[lng],[lat]/predictions是你想要的那么lng& lat不是查询字符串参数,而是URI路径的一部分。您可以完全跳过查询字符串并将requestOptions更改为:

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