这可能是一个简单的问题,但我是云功能/节点编程的新手,还没有找到合适的文档。
如何编写将接收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
}
};
答案 0 :(得分:11)
这是我设法在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函数在哪里打印出信息。这可能对将来的调试很有帮助。
答案 1 :(得分:4)
Request模块使用回调。如果您想使用JavaScript promises,Axios模块提供了相同的功能。
答案 2 :(得分:2)
使用https://www.npmjs.com/package/request模块。
var request = require('request');
request.get('https://maker.ifttt.com/trigger/arrive/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.
});
答案 3 :(得分:2)
岁,但是我在搜索自己时遇到了这个问题:
具有承诺支持的请求模块是(request-promise)