Reputation: 11753
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/[email protected]
I get what I expect in the logs, that is:
myFunc: From (URL): [email protected]
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("[email protected]");
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 ?
Upvotes: 0
Views: 121
Reputation: 11753
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: '[email protected]'
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log('THE DATA:',data);
};
Upvotes: 1