无法使用Node.js服务器连接到Google Directions API [英] Cannot connect to Google Directions API with Node.js server
问题描述
我正在尝试通过回调函数通过节点服务器连接到Google Directions API,但由于某种原因,我无法从Google API得到响应。有趣的是,几天前我做了这个工作,然后设法以某种方式打破了它。我的控制器包含以下代码-调用google_api.js中的函数:
I am trying to connect to the Google Directions API with my node server via a callback function but for some reason I cannot get a response from the Google API. Funny enough I had this working a few days ago and somehow I managed to break it. My controller contains the following code - calling a function within 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密钥):
My google_api.js file contains the following code (with a valid API key):
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错误的错误,但复制此错误并不一致。我担心自己缺少一些基本知识,甚至都不知道从哪里开始。任何帮助将是巨大的!谢谢
console.log("First"), console.log("Second") and console.log(req) all behave as expected so the problem must exist inside the googleMapsClient.directions() function. The API key is tested and works with another front-end JS function so it isn't a problem with the key. I managed to get the function to output an error once with a EHOSTUNREACH error but replicating this has not been consistent. I fear I am missing something so basic that I don't even know where to begin. Any help would be great! Thanks
推荐答案
**
很久以前问过,只要有人遇到问题并想要
实施此Google api,就发布一个工作代码。 / p>
Asked long time ago, just posting a working code if anybody comes across and want to implementing this 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)
});
这篇关于无法使用Node.js服务器连接到Google Directions API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!