0

使用 request promise 模块进行 post 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)

如何解决控制台记录城市数据的错误?

4

1 回答 1

0

console.log(response.results[0].formatted_address)

于 2018-02-12T12:54:09.263 回答