node.js - 如何从 Google Cloud Functions (nodeJS) 发送 HTTP 请求

标签 node.js httprequest google-cloud-functions

这可能是一个简单的问题,但我是云函数/Node 编程的新手,还没有找到合适的文档。

如何编写将接收 HTTP 请求但随后将 HTTP 请求发送到不同端点的 Google 云函数?例如,我可以将 HTTP 触发器发送到我的云函数 ( https://us-central1-plugin-check-xxxx.cloudfunctions.net/HelloWorldTest )。在项目的后期,我将弄清楚如何实现延迟。但后来我想用一个新的 HTTP 请求响应到不同的端点 (https://maker.ifttt.com/trigger/arrive/with/key/xxxx)。我怎么做?

exports.helloWorld = function helloWorld(req, res) {
  // Example input: {"message": "Hello!"}
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);
    res.status(200).send('Success: ' + req.body.message);
    // ??? send a HTTP request to IFTTT endpoint here
  }
};

最佳答案

这是我在 Chetan Kanjani 的帮助下设法获得的代码。当我向我的 Google Cloud 函数端点发送短信时,它会回复一条短信给 IFTTT(另一个端点)。

const request = require('request');

exports.helloWorld = function helloWorld(req, res) {
  // Example input: {"message": "Hello!"}
  if (req.body.message === undefined) {
    // This is an error case, as "message" is required.
    res.status(400).send('No message defined!');
  } else {
    // Everything is okay.
    console.log(req.body.message);

    request.get('https://maker.ifttt.com/trigger/arrival/with/key/xxxx', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred 
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
      console.log('body:', body); //Prints the response of the request. 
    });
    res.status(200).send("Success");
  }
};

我还必须更改 package.json 文件以包含请求包。它已经有了 sample-http 包,我添加了依赖项:

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "request": "^2.81.0"
  }
}

我仍然不确定 console.log 函数在哪里打印信息。这可能对以后的调试有帮助。

关于node.js - 如何从 Google Cloud Functions (nodeJS) 发送 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44277175/

相关文章:

mysql - 无法获取和读取 GET 请求

javascript - xmlhttprequest responsetext 来接受 header : text/xml , 但应用程序/JSON 的服务器错误

firebase - 尝试按照部署指令部署多个功能导致错误,arg 太多

javascript - 在循环中收集 Firebase 云函数异步调用的结果

node.js - socket.io:高流量时出现错误请求错误

sql-server - 请求错误 : { message: 'Requests can only be made in the LoggedIn state, not the SentLogin7WithStandardLogin state' , 代码: 'EINVALIDSTATE' }

javascript - 将拒绝/解决添加到捕获/成功

c# - 触发多个可能需要很长时间的 HttpWebRequest 的正确方法

c# - HTTPRequest 后的后台代理 notifyComplete()

node.js - 为什么 Puppeteer 需要 --no-sandbox 在 Cloud Functions 中启动 Chrome