0
我一直在自学Node.js和Express,并试图从Google Maps Geocoding API请求中返回JSON结果。我得到它使用require
模块的工作,但我试图找出我做错了什么Express中让我领悟了:获取Google地图从快速地理编码JSON
快速尝试:htmlController.js
// FYI: This controller gets called from an app.js file where express() and
// the mapsAPI is passed as arguments.
var urlencodedParser = bodyParser.urlencoded({extended: false});
module.exports = function(app, mapsAPI){
app.post('/maps', urlencodedParser, function(req,results){
var lat;
var long;
var add = req.body.add;
app.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + add + '&key=' + mapsAPI, function(req,res){
lat = res.results.geometry.northeast.lat;
long = res.results.geometry.northeast.long;
console.log(lat); // no output
console.log(lat); // no output
}, function(){
console.log(lat); // no output
console.log(long); // no output
});
results.send("Thanks!");
});
}
正如你所看到的,我试图用不同的代码块记录它,但API请求中的任何日志都没有显示给控制台。
使用require
模块工作要求:
app.post('/maps', urlencodedParser, function(req,results){
var add = req.body.add;
request({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + add + '&key=' + mapsAPI,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
}
});
results.send("Thanks!");
});
啊我看你在说什么。我用'request'工作,我想知道是否有办法做到这一点,但没有它,只有通过使用Express。 –
使用节点内置'http'模块 [请参阅示例代码](https://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request) –