URL에 쿼리 문자열 매개 변수를 추가하는 방법에 어려움을 겪고 있습니다. 내 URL 끝에 ?
을 추가해야한다는 것을 알기 전까지는 작동하지 못했습니다. 그렇지 않으면 작동하지 않습니다. 이것은 디버깅에 몇 시간을 절약 할 수 있기 때문에 매우 중요합니다. 나를 믿으십시오. ... been done .... 다음은
는 Open Weather API를 호출하고 쿼리 매개 변수로 APPID
, lat
및 lon
를 전달하고 JSON
대상으로 기상 데이터를 반환하는 간단한 API 엔드 포인트입니다. 희망이 도움이됩니다.
//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) {...})
http://nodejs.org/api/url.html#url_url_format_urlobj – SLaks
https://nodejs.org /api/querystring.html – velop