8

I have the following hello world Firebase cloud function:

const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("Hello from Firebase!");
});

I then call it from a webpage, like so:

<script>
    // Initialize Firebase
    var config = { <config information copy-pasted from firebase console>
    };
    firebase.initializeApp(config);

    let helloWorld = firebase.functions().httpsCallable('helloWorld');
    console.log(helloWorld)
    helloWorld().then(function (result) {

    })
</script>

However, I get the following error:

Access to fetch at (my cloud func url) from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I can still access the HTTP endpoint directly. What am I doing wrong?

I tried the following after looking at: Enabling CORS in Cloud Functions for Firebase:

const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {

    return cors(req, res, () => {
        res.status(200).send('Hello World!')
    })
    //response.set('Access-Control-Allow-Origin', '*');
    //response.send("Hello from Firebase!");
});

But, when I visit the HTTP endpoint, I get the error:

Error: could not handle the request

Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Can try replace `functions.https.onRequest` with `functions.https.onCall(data =>` since you are calling `firebase.functions().httpsCallable('helloWorld')` and remove cors and return a simple string `return "Hello World"` – Philip Nov 04 '18 at 11:10
  • try using onCall as explained here: https://stackoverflow.com/questions/51066434/firebase-cloud-functions-difference-between-onrequest-and-oncall?noredirect=1&lq=1 – cbeltrangomez May 07 '20 at 06:49

0 Answers0