【问题标题】:Calling http GET requests from ibm cloud functions using nodejs使用 nodejs 从 ibm 云函数调用 http GET 请求
【发布时间】:2019-01-27 07:35:14
【问题描述】:

在开发云功能时出现以下错误。

我创建了一个云操作,并在 watson 帮助中的 json 响应中使用了该操作名称。然后一旦匹配了意图,它就会调用云函数。我选择nodejs作为云功能的开发语言。

现在我真正的要求是从该云函数调用 https 获取请求。为此,我需要使用名为 node-rest-client 的 nodejs 库。

通常我们需要在终端中输入“npm install node-rest-client”来安装它。由于我得到的 IBM nodejs 编辑器中没有终端,请您告诉我该怎么做。

作为替代,我使用了已经在 nodejs 包中的 https 库。并在编辑器中编写了如下代码

const https = require('https');

function main() {
    https.get('https://f6054382.ngrok.io/webhook/testRequest', (resp) => {
        resp.on('data', (d) => {
            process.stdout.write(d);
        });
    });
}

main();

一旦我在本地文件夹中键入“node init”并将上面的代码添加到 index.js 文件中,然后使用命令“node index.js”运行它,代码就可以通过给我来自 web 服务的预期输出成功地工作。

但我在 IBM nodejs 编辑器中没有得到该结果

https://console.bluemix.net/openwhisk/details/action/dialogif.psi%2540gmail.com_dev/webhookCall/code

一旦我保存了上面的代码并通过点击右上角的按钮来调用,我会得到如下绿色的成功响应。

激活 ID: 341d4e5bc81f4e489d4e5bc81f2e4888 结果: {} 日志: []

你能帮我解决这个问题吗

谢谢

【问题讨论】:

    标签: node.js ibm-cloud ibm-watson openwhisk


    【解决方案1】:

    执行异步操作时,例如HTTP 请求,您需要从操作处理程序返回一个 Promise。这可确保平台在完成调用之前阻塞该异步结果。

    function main() {
        return new Promise((resolve, reject) => {
            https.get('https://f6054382.ngrok.io/webhook/testRequest', (resp) => {
            resp.on('data', (d) => {
                process.stdout.write(d);
                resolve({})
            });
        });
      })        
    }
    

    【讨论】:

      【解决方案2】:

      根本问题是您的代码运行 asynchronously 并且没有返回 Promise 以指示将来会提供结果。

      我建议使用request-promises,它来自pre-packaged with OpenWhisk's Node.js runtime

      const request = require('request-promise');
      
      function main(params) {
          return request("https://f6054382.ngrok.io/webhook/testRequest").then(response => {
              process.stdout.write(response);
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-01
        • 2021-04-11
        • 2019-09-17
        • 2019-04-14
        • 1970-01-01
        • 2018-01-22
        • 2017-11-09
        • 1970-01-01
        相关资源
        最近更新 更多