我一直在苦恼如何向我的URL添加查询字符串参数。 直到意识到需要在我的URL末尾添加
?
,否则它将无法正常工作。 这非常重要,因为它可以节省您数小时的调试时间,相信我:我已经经历过了。
下面是一个简单的API端点,调用
Open Weather API并将
APPID
,
lat
和
lon
作为查询参数传递,并返回天气数据作为
JSON
对象。 希望这可以帮助到您。
var request = require('request');
var querystring = require('querystring');
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);
} else if(response && body) {
console.log('statusCode:', response && response.statusCode);
res.json({'body': body});
}
})
})
如果您想使用
querystring
模块,请进行以下更改。
var queryObject = querystring.stringify({
APPID: OpenWeatherAppId.appId,
lat: req.body.lat,
lon: req.body.lon
});
request({
url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})