【问题标题】:Cannot connect to Google Directions API with Node.js server无法使用 Node.js 服务器连接到 Google Directions API
【发布时间】:2017-02-21 22:19:23
【问题描述】:

我正在尝试通过回调函数使用我的节点服务器连接到 Google Directions API,但由于某种原因,我无法从 Google API 获得响应。有趣的是,几天前我有这个工作,不知何故我设法打破了它。我的控制器包含以下代码 - 在 google_api.js 中调用函数:

var google = require('../scripts/google_api')    

var inputs = {
  origin: "1600 Amphitheatre Parkway, Mountain View, CA",
  destination: "1 Infinite Loop, Cupertino, CA 95014, USA",
  mode: "driving",
};

function getDirections(data, callback){
  console.log("First");
  callback(data);
  console.log("Second");
};
getDirections(inputs, google.directions);

我的 google_api.js 文件包含以下代码(使用有效的 API 密钥):

var googleMapsClient = require('@google/maps').createClient({
  key: 'XXX'
});

module.exports.directions = (req, res) => {

  console.log(req);

  googleMapsClient.directions({
  origin: req.origin,
  destination: req.destination,
  mode: req.mode,

  }, function(err, response) {
    if (!err) {
    console.log(response.json.results);
    };
  });
};

console.log("First")、console.log("Second") 和 console.log(req) 都按预期运行,因此问题必须存在于 googleMapsClient.directions() 函数中。 API 密钥经过测试,可与另一个前端 JS 函数一起使用,因此密钥没有问题。我设法让函数输出一个错误,并出现 EHOSTUNREACH 错误,但复制它并不一致。我担心我错过了一些如此基本的东西,以至于我什至不知道从哪里开始。任何帮助都会很棒!谢谢

【问题讨论】:

    标签: javascript node.js api callback google-api


    【解决方案1】:
    **
    

    很久以前问过,如果有人遇到并想要发布一个工作代码 实现这个 google api。

    **

    var googleMapsClient = require('@google/maps').createClient({
      key: xxxxxxxxxx
    });
    
    function getDirections (req, callback)  {
      googleMapsClient.directions({
      origin: req.origin,
      destination: req.destination,
      mode: req.mode,
    
      }, function(err, response) {
      console.log(err);
      console.log(response);
        if (!err) { 
        callback(response.json.results);
        };
      });
    };
    
    var inputs = {
      origin: "1600 Amphitheatre Parkway, Mountain View, CA",
      destination: "1 Infinite Loop, Cupertino, CA 95014, USA",
      mode: "driving",
    };
    
    getDirections(inputs, function(result){
    console.log("Response: ", result)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 2014-06-28
      • 2019-09-29
      • 1970-01-01
      • 2015-07-27
      相关资源
      最近更新 更多