2016-01-21 40 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) –

相關問題