我一直在努力解决如何将查询字符串参数添加到我的 URL。直到我意识到我需要?
在我的 URL 末尾添加,我才能让它工作,否则它不会工作。这非常重要,因为它可以为您节省数小时的调试时间,相信我:去过那里...做过。
下面是一个简单的 API Endpoint,它调用Open Weather API并传递APPID
,lat
和lon
作为查询参数并将天气数据作为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) {...})