0

Here is the code for a working firebase cloud function and following is a question about some change I want to make and can't at this point, even after trying several options.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from "cors";

const corsHandler = cors({origin: true});

admin.initializeApp(functions.config().firebase);

exports.myFunc = functions.https.onRequest(function(req, resp) {
  corsHandler(req, resp, async () => {
    const from = String(req.query.from); // Through the URL.
    // const from = req.body.from; // I tried this among other things to get the    information through a POST but it did not work.
    admin.auth().getUserByEmail(from)
        .then(function(userRecord) {
          console.log("Successfully fetched user data:", 
                      userRecord.toJSON());
        })
        .catch(function(error) {
          console.log("Error fetching user data:", error);
        });
  });
});

This function can be called using a URL like:

https://us-central1-myapp.cloudfunctions.net/myFunc?from=example@example.com

But what I want is to be able to call it through a POST from a JS page (with XMLHttpRequest) in my web app.

How should I change the function above for that?

For reference, this is the kind of code I am trying to use on the web-app side to call the cloud function (but it is not working):

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp.cloudfunctions.net/myFunc", true, 'me@example.com', 'VerySecretPassWord');

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send({"from": "example@example.com"});
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};
Michel
  • 10,303
  • 17
  • 82
  • 179
  • 2
    Please include the code you are using to make the request from the client. Consider using a [Callable Function](https://firebase.google.com/docs/functions/callable) instead if using the client SDKs. Aside from that, in the above shared code, you aren't returning the data to the caller and `functions.config().firebase` is always `undefined` (it was removed years ago) - use `initializeApp()` (no arguments) for the same effect. – samthecodingman Jan 29 '22 at 10:11
  • @samthecodingman. I made an addition to my post to provide the information you need. Please have a look at the end. As you say "I am not returning the data to the caller" at this stage. I am just looking at the logs to make sure the function is called correctly first. But this is not the case. I will worry later about returning data, of course. – Michel Jan 30 '22 at 04:27
  • You may have a look at the [Stackoverflow case](https://stackoverflow.com/questions/43415759/use-firebase-cloud-function-to-send-post-request-to-non-google-server). – Mousumi Roy Mar 18 '22 at 11:32

0 Answers0