HTTP POST Google Cloud Functions NodeJS

戏子无情 提交于 2020-07-07 06:02:42

问题


How do I write a Google Cloud Function that will receive a HTTP request and then send a HTTP POST request to a different endpoint?

For example,

  • I can send the HTTP trigger to my cloud function (https://us-central1-plugin-check-xxxx.cloudfunctions.net/test). I am using exports.test = function helloWorld(req, res){} to process the data received.

  • And then I want to send the processed data with a HTTP POST request to a different endpoint.

By far I have tried sending HTTP POST with node-webhooks, request & restler modules but none of them seem to work. Is it because these modules are used in conjunction with exports.test ?

My question is related to this question but the answers didn't help me.

The data being sent to endpoint is in json & Content-type: application/json.

var request = require('request'); //also tried for node-webhook, restler modules

exports.test = function(req, res) {
 //processing of received json data from source A. 
}

function sendToEndpoint(processed_data) {

  let abc = processed_data;   //send processed data to source B 

  request.post({
      uri: 'https://example.com',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(abc)
  }); 

}

回答1:


As @RenaudTarnec mentioned in the comments the problem was that my billing account was not configured.

Google doesn't allow outbound requests to external servers without valid billing info so as to prevent any malicious activity.

After configuring a billing account I was able to make outbound requests and all the node-modules mentioned in the question worked.




回答2:


Within a Cloud Function that is written in Node.js, you can use any package that is accessible via NPM. Using Google Search to find such packages shows:

  • 5 Ways to Make HTTP Requests in Node.js
  • Calling a REST API from a NodeJS Script
  • REST Client for Node.js
  • 4 + 1 ways for making HTTP requests with Node.js: async/await edition
  • Unirest for Node.js
  • ... others

Which one you choose is usually a matter of taste. My personal choice is to use the one which does the job and is most popular. I equate popularity with liklihood of on-going support and updates.




回答3:


Use Websockets SOCKET.IO is the best choice. https://socket.io/

However it is impossible to use this in cloud functions. Because it is distributed in different machines. So keeping track is impossibe.



来源:https://stackoverflow.com/questions/55836218/http-post-google-cloud-functions-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!