我一直在努力解决如何将查询字符串参数添加到我的 URL。直到我意识到我需要在我的 URL 末尾添加 ? 之前,我才能让它工作,否则它将无法工作。这一点非常重要,因为它可以为您节省数小时的调试时间,相信我:去过那里......完成了。
下面是一个简单的 API 端点,它调用 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) {...})