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 ?