0

I am having trouble adjusting the code (using cors) for a firebase cloud function I am working on.

Below is the code for the function:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from "cors";
import { on } from "events"

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

exports.myFunc = functions.https.onRequest(function(req,    resp) {
  corsHandler(req, resp, async () => {
    if (req.query.from !== undefined) {
      const from = String(req.query.from);
      functions.logger.log("From (URL):", from);
    } else {
      functions.logger.log("req.query.from is undefined");
    }

    const from = req.body.from;
    functions.logger.log("Hello from --myFunc--");

    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);
        });
  }); // End corsHandler.
});

When I call this function using this URL in the browser:

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

I get what I expect in the logs, that is:

myFunc: From (URL): example@example.com

On the other hand when I call the function using this Ajax code from a web-app:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/myFunc", true);
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);
};

I have a problem, getting the following in the web console logs:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myFunc. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.

I must be missing something. Can someone point out what it is ?

Michel
  • 10,303
  • 17
  • 82
  • 179
  • Can you change `corsHandler` to `cors` and see if it resolves the issue? If that does not help, can you try out as mentioned in [this answer](https://stackoverflow.com/a/43418322/15746749), which is also specified in [this document](https://cloud.google.com/functions/docs/samples/functions-http-cors#code-sample)? – Prabir Jan 31 '22 at 13:47
  • On which line do you want to change corsHandler to cors. corsHandler appears in 2 places in the code and cors is already used. I made a quick trial but only get errors. I need to say I do not actually understand how it could make any difference. But if you have a good idea I am willing to try it of course. – Michel Jan 31 '22 at 14:44
  • @Prabir. I spent some time working to try the second part of your comment (following the answer you mention and reading the document), but I still get the same error message as before. And more over the execution does not even reach the inside of the functions.https.onRequest(function(req,resp) {...} block. So not getting a chance to use the added code (i.e. resp.set("Access-Control-Allow-Origin", "*"); ... etc ....). – Michel Feb 01 '22 at 04:28
  • Can you tell how you came to know that the execution is not reaching inside of the function block? Are you getting any errors? If the code inside the block is not getting executed then it seems there is some issue with your function code. – Prabir Feb 03 '22 at 11:23
  • @Prabir. I came to that conclusion because the message that I had put in the code was not appearing in the logs. But after more experimenting I made some progress since then and solved that problem. – Michel Feb 04 '22 at 13:46
  • Nice to hear that the issue got resolved. It will be beneficial to the community members if you can post an answer so that others can refer to it when they face similar kinds of issues. – Prabir Feb 08 '22 at 13:07
  • Yes you're right. I did it. – Michel Feb 12 '22 at 08:10

1 Answers1

1

I finally got it to work, using this code for the Ajax call from the web-app (hoping this might help someone facing the same kind of issue at some point):

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp. cloudfunctions.net/    myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    from: 'example@example.com'
}));
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};
Michel
  • 10,303
  • 17
  • 82
  • 179