Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase cloud functions make a POST request [duplicate]

I am using firebase database and I want a cloud function(trigger) to communicate with a REST node.js webservice I have.

The trigger is already created, but now I want that the cloud function to call a external webservice I have in a hosted machine.

I imported jQuery. But it says that $.post is not a function. I thought it would be because the slim version was installed somehow(not the case). Then I tried to do it directly in JavaScript using XMLHttpRequest, which the function also says

ReferenceError: XMLHttpRequest is not defined at /user_code/index.js:91:19 at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Do you have any clue how to make a POST request on firebase cloud functions?

like image 297
João Mourão Avatar asked Apr 07 '26 19:04

João Mourão


2 Answers

You have to be on a paid firebase plan (possibly Blaze) in order to POST to an external website. https://stackoverflow.com/a/42775841/6480950

Can use npm modules request & request promise.

Basic Test: https://stackoverflow.com/a/43645498/6480950

like image 151
Arkelyan Avatar answered Apr 09 '26 07:04

Arkelyan


Firebase Cloud Functions is a Node.js environment. But jQuery is a client-side javascript library. There are a few server-side jQuery builds (Cheerio, nodeQuery), see here: Can I use jQuery with Node.js?

But I would . . .

try using node module xmlhttprequest. It let's you write raw requests the way you would in client-side JavaScript. You'll need that dependency in your package.json file ie:

"dependencies": {
    "xmlhttprequest": "^1.8.0"
}

Then in your function:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var request = new XMLHttpRequest();
request.addEventListener('load', doSomethingWithDataFromResponse);
request.open("GET","http://urlToMyServer");  
request.send();

function doSomethingWithDataFromResponse() {
  var data = this.responseText;
  //etc.
}

For a POST something like:

var request = new XMLHttpRequest();
var params = "word=foo"; //or stringify some JSON
request.addEventListener('load', doSomethingWithDataFromResponse);
request.open("POST","http://urlToMyServer"); 
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // or application/json etc.
request.send(params);

That's how I've been doing requests from a node server to other third-party servers lately. I haven't had a chance to try it with Firebase yet, but all documentation seems to indicate that it should work.

like image 25
DMS Avatar answered Apr 09 '26 09:04

DMS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!