使用查询string参数的node.js http'get'请求

我有一个Node.js应用程序是一个HTTP客户端(目前)。 所以我在做:

var query = require('querystring').stringify(propertiesObject); http.get(url + query, function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); 

这似乎是一个很好的方法来完成这一点。 不过,我有点恼火,我不得不做的url + query步骤。 这应该被一个共同的库封装,但我没有看到这个节点的http库中存在,我不知道什么标准的NPM包可能会实现它。 有一个相当广泛的使用方式更好吗?

url.format方法保存了构build自己的URL的工作。 但理想情况下,这个要求也会比这更高。

检出请求模块。

它比节点的内置http客户端function更全面。

 var request = require('request'); var propertiesObject = { field1:'test1', field2:'test2' }; request({url:url, qs:propertiesObject}, function(err, response, body) { if(err) { console.log(err); return; } console.log("Get response: " + response.statusCode); }); 

如果您不想使用外部软件包,只需在您的实用程序中添加以下function:

 var params=function(req){ let q=req.url.split('?'),result={}; if(q.length>=2){ q[1].split('&').forEach((item)=>{ try { result[item.split('=')[0]]=item.split('=')[1]; } catch (e) { result[item.split('=')[0]]=''; } }) } return result; } 

然后,在createServercallback中,添加属性paramsrequest对象:

  http.createServer(function(req,res){ req.params=params(req); // call the function above ; /** * http://mysite/add?name=Ahmed */ console.log(req.params.name) ; // display : "Ahmed" }) 

我一直在努力如何将查询string参数添加到我的url。 直到我意识到我需要添加才能使其工作? 在我的URL的末尾,否则它将无法正常工作。 这是非常重要的,因为它会节省你几个小时的debugging时间,相信我: 在那里…做到了

下面是一个简单的API端点,它调用Open Weather API并传递APPIDlatlon作为查询参数,并将天气数据作为JSON对象返回。 希望这可以帮助。

 //Load the request module var request = require('request'); //Load the query String module var querystring = require('querystring'); // Load OpenWeather Credentials var OpenWeatherAppId = require('../config/third-party').openWeather; router.post('/getCurrentWeather', function (req, res) { var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?' var queryObject = { APPID: OpenWeatherAppId.appId, lat: req.body.lat, lon: req.body.lon } console.log(queryObject) request({ url:urlOpenWeatherCurrent, qs: queryObject }, function (error, response, body) { if (error) { console.log('error:', error); // Print the error if one occurred } else if(response && body) { console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received res.json({'body': body}); // Print JSON response. } }) }) 

或者,如果您想使用querystring模块,请进行以下更改

 var queryObject = querystring.stringify({ APPID: OpenWeatherAppId.appId, lat: req.body.lat, lon: req.body.lon }); request({ url:urlOpenWeatherCurrent + queryObject }, function (error, response, body) {...})