0

As the title suggests, I have a web app that calls a Firebase cloud function, but it doesn't work because of a cross-origin policy. I've seen many solutions on this site, but none work. I tried an answer from another StackOverflow question but nothing worked at all.

code in index.html:

            firebase
            .functions()
            .httpsCallable("addMessage")()
            .then((res) => {
                console.log(res);
            });

code in index.js (the cloud function):

exports.addMessage = onRequest(async (req, res) => {
    // Grab the text parameter.
    const original = req.query.text;
    // Push the new message into Firestore using the Firebase Admin SDK.
    const writeResult = await getFirestore().collection("messages").add({ original: original });
    // Send back a message that we've successfully written the message
    res.set("Access-Control-Allow-Origin", "*");
    res.json({ result: `Message with ID: ${JSON.stringify(original)} added.` });
});

the error:

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

I'm very confused on how these solutions even worked for other people as this seems to be a client-side problem and nothing added to the cloud function should fix it. please help!

altywalty
  • 55
  • 6
  • the fact that the status code is 403 (*forbidden*) suggests the *cloud function* you posted is NOT the code that is responsible for the response – Jaromanda X Jul 02 '23 at 02:37
  • @JaromandaX In the Firebase cloud functions console, I can see the invocations of trying to call it. I'm also a beginner so it could just be a small mistake. – altywalty Jul 02 '23 at 04:33
  • perhaps `await getFirestore().collection("messages").add({ original: original });` is failing ... you have no `try/catch` to handle promise rejection – Jaromanda X Jul 02 '23 at 04:37
  • @JaromandaX Even with the entire function body empty, the error is the same. – altywalty Jul 02 '23 at 04:51
  • therefore it has nothing to do with that function as I stated earlier - 403 means forbidden – Jaromanda X Jul 02 '23 at 05:05
  • @JaromandaX Firebase docs don't show anything about being able to get past this. All I'm trying to do is call a cloud function from my web app and get a returned value from it. – altywalty Jul 02 '23 at 18:54
  • https://stackoverflow.com/questions/76600481/firebase-make-call-to-cloud-function-without-no-cors-option/76600762#76600762 – altywalty Jul 03 '23 at 00:36

0 Answers0