I am trying to add query string parameters to my URL. I couldn't get it to work until I realized what I needed to add ? at the end of my url, otherwise it won't work. This is very important, as it will save you hours of debugging, believe me: I was there ... did it .
The following is a simple API endpoint that calls the Open Weather API and passes APPID , lat and lon as request parameters and return weather data as a JSON object. Hope this helps.
//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. } }) })
Or, if you want to use the querystring module, make the following changes
var queryObject = querystring.stringify({ APPID: OpenWeatherAppId.appId, lat: req.body.lat, lon: req.body.lon }); request({ url:urlOpenWeatherCurrent + queryObject }, function (error, response, body) {...})
AllJs Mar 19 '17 at 12:28 2017-03-19 12:28
source share