2
votes

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,

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)
  }); 

}
3
@RenaudTarnec, no my question is not related to that. I have no problem in receiving the data. I am facing trouble in making a HTTP(s) POST request from cloud function. - Electric_90
This is exactly what this answer is covering: how to issue a POST HTPP Request to an external endpoint, from the Cloud Function. - Renaud Tarnec
Please show some code you tried and what was the result. - Molda
@Electric_90 To be honest I don't know... my experience with Cloud Functions is limited to Firebase ones, deployed through the Firebase CLI. But from what I know, there shouldn't be any difference in this case. Only point I cazn see is that with Firebase CF, you need to be on the "Flame" or "Blaze" pricing plan. - Renaud Tarnec

3 Answers

2
votes

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.

1
votes

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:

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.

0
votes

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.