如何在 actions-on-google 中使用 API

How to use API in actions-on-google

我尝试了以下 javascript 代码,使用 aog 中的铁路 API 来获取 2 个车站之间的火车名称。

train : function(conv,src,dst) {
const options={
    method:'GET',
    url : `https://api.railwayapi.com/v2/between/source/${src}/dest/${dst}/date/23-09-2018/apikey/<api_key>/`,
    json : true
};
var data=[];
return rp(options)
    .then(function(parseBody){

    for(var i=0;i<2;i++){
        data.push(parseBody.trains[i].name);

    }
    console.log(data);
    return conv.ask(data[0] + data[1]);
}).catch(err=>{
    console.log("api error" + err);
});
}

当我 运行 在我的计算机中使用终端(节点 filename.js)时,它显示具有正确值的数据 [] 数组。但是当我尝试从 actions-on-google 模拟器中 运行 它时,它会捕获如下错误...

api errorRequestError: Error: getaddrinfo ENOTFOUND api.railwayapi.com api.railwayapi.com:443

如果您尝试使用 Firebase Cloud Functions (FCF) 或 Dialogflow 内置编辑器(在幕后使用 FCF)执行此操作,最可能的原因是您使用的是 FCF 的免费层不允许在 Google 的网络之外进行呼叫。

您可以从 Google 升级到 Blaze Plan to get around this. While this does require a credit card to be on file, it includes a free tier which is quite sufficient for some basic testing and probably even some very light usage once you're in production. Once you have your Action approved, you will be eligible to receive cloud credits,这可用于抵消与使用 Cloud Functions 相关的费用。