【问题标题】:How to call an API inside a cloud function?如何在云函数中调用 API?
【发布时间】:2019-07-28 01:27:15
【问题描述】:

我正在使用 Dialogflow 和 Cloud Functions 在 Google 聊天机器人上开发 Actions。运行时是 Node.js 6。

为什么这个函数返回空字符串?

function getJSON(url) {
  var json = "";
  var request = https.get(url, function(response) {
    var body = "";
    json = 'response';
    response.on("data", function(chunk) {
      body += chunk;
      json = 'chunk';
    });
    response.on("end", function() {
      if (response.statusCode == 200) {
        try {
          json = 'JSON.parse(body)';
          return json;
        } catch (error) {
          json = 'Error1';
          return json;
        }
      } else {
        json = 'Error2';
        return json;
      }
    });
  });
  return json;
}

这是我想要访问 json 数据的意图:

app.intent('test', (conv) => {
conv.user.storage.test = 'no change';
const rp = require("request-promise-native");
var options = {
    uri: 'https://teamtreehouse.com/joshtimonen.json',
    headers: {
        'User-Agent': 'Request-Promise'
    },
    json: true // Automatically parses the JSON string in the response
};

rp(options)
    .then(function (user) {
        conv.user.storage.test = user.name;
    })
    .catch(function (err) {
        conv.user.storage.test = 'fail';
    });
conv.ask(conv.user.storage.test);
});

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-functions dialogflow-es dialogflow-es-fulfillment


    【解决方案1】:

    您可以尝试将request 模块用于node.js,我尝试自我复制您的用例并且工作正常。代码应该是这样的:

    const request = require('request');
    
    request(url, {json: true}, (err, res, body) => {
      if (err) { res.send(JSON.stringify({ 'fulfillmentText': "Some error"})); }
        console.log(body);
      });

    另外,您需要在 package.json 文件中的 dependencies 部分添加 "request": "2.81.0"

    【讨论】:

    • 好的,你能解释一下如何访问我 Intent 中的 JSON 对象吗?
    【解决方案2】:

    函数返回空字符串是因为https设置了回调函数,但程序流程继续执行回调之前的return语句。

    通常,在使用 Dialogflow Intent 处理程序时,您应该返回 Promise 而不是使用回调或事件。考虑改用request-promise-native

    两个澄清点:

    • 必须返回 Promise。否则 Dialogflow 将假定 Handler 已完成。如果您返回 Promise,它将等待 Promise 完成。
    • 您想要发回的所有内容都必须在then() 块内完成。这包括设置任何响应。 then() 块在异步操作(Web API 调用)完成后运行。所以这会有调用的结果,你可以在你的调用中将这些结果返回给conv.ask()

    所以它可能看起来像这样:

      return rp(options)
        .then(function (user) {
          conv.add('your name is '+user.name);
        })
        .catch(function (err) {
          conv.add('something went wrong '+err);
        });
    

    【讨论】:

    • 谢谢!我仍然不明白如何访问 json 数据。我已将测试意图的代码添加到我的问题中。
    • 希望得到澄清。
    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    相关资源
    最近更新 更多