2016-01-21 46 views
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!"); 
}); 

回答

1

如果我理解正确的话,你正在尝试使用app.get()

app.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + add + '&key=' + mapsAPI, function(req,res){} 

app.get()函数来获取从Google地图API的数据用于仅适用于您的应用路由,而不是获取远程数据。同为router.get()

// app.get(appRoute, middlewareORhandler) 
app.get('/myOwnApp/api/users/12/', function(res,res,next)){ 
    // your code here 
    res.status(200).send("return your response here"); 
} 

,使您可以使用内置的http模块的远程请求。 requestsuperagent是巨大的,容易使远程请求

安装这些模块:

npm install request --save 
var request = require('request'); 

npm install superagent --save 
var request = require('superagent'); 

看到更多:https://www.npmjs.com/package/request

+0

啊我看你在说什么。我用'request'工作,我想知道是否有办法做到这一点,但没有它,只有通过使用Express。 –

+0

使用节点内置'http'模块 [请参阅示例代码](https://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request) –

相关问题