使用请求承诺模块进行后API调用。代码是为了获得城市'来自谷歌地图api JSON输出的详细信息如下:
var rp = require('request-promise');
............
app.get('/check_promise', function(req,res) {
var option1 = {
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=Florence',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: true
}
rp(option1)
.then(function(response) {
console.log(response.data.results[0].formatted_address);
})
.catch(function(error){
console.log(error);
});
});
但是
console.log(response.data.results[0].formatted_address);
给出以下错误:
TypeError: Cannot read property 'results' of undefined
at C:\Users\Laxmi\devapp\server.js:208:33
at tryCatcher (C:\Users\Laxmi\devapp\node_modules\bluebird\js\release\util.j
s:16:23)
at Promise._settlePromiseFromHandler (C:\Users\Laxmi\devapp\node_modules\blu
ebird\js\release\promise.js:512:31)
at Promise._settlePromise (C:\Users\Laxmi\devapp\node_modules\bluebird\js\re
lease\promise.js:569:18)
at Promise._settlePromise0 (C:\Users\Laxmi\devapp\node_modules\bluebird\js\r
elease\promise.js:614:10)
at Promise._settlePromises (C:\Users\Laxmi\devapp\node_modules\bluebird\js\r
elease\promise.js:693:18)
at Async._drainQueue (C:\Users\Laxmi\devapp\node_modules\bluebird\js\release
\async.js:133:16)
at Async._drainQueues (C:\Users\Laxmi\devapp\node_modules\bluebird\js\releas
e\async.js:143:10)
at Immediate.Async.drainQueues (C:\Users\Laxmi\devapp\node_modules\bluebird\
js\release\async.js:17:14)
at runCallback (timers.js:789:20)
at tryOnImmediate (timers.js:751:5)
at processImmediate [as _immediateCallback] (timers.js:722:5)
如何解决错误以控制记录城市数据?
答案 0 :(得分:0)
console.log(response.results[0].formatted_address)