Skip to content
Advertisement

Invoking Firebase Function from Firebase hosting code blocked by CORS

I’ve initialized a templated Firebase project with functions & hosting features.

I’ve uncommented the templated HTTP function:

export const helloWorld = functions.https.onRequest((req, res) => {
  functions.logger.info("Hello logs!", {structuredData: true});
  res.send("Hello from Firebase!");
});

And Also added the following code to the templated public/index.html file:

const functions = firebase.functions();
const helloWorld = functions.httpsCallable('helloWorld');
helloWorld().then((res) => { console.log(res); });

I’ve tried making this work with multiple configurations:

  1. Firebase emulator for hosting, invoking the deployed Firebase function.
  2. Firebase emulator for hosting, invoking the emulated function (Firebase functions emulator).
  3. The deployed hosting, invoked the deployed Firebase function.

All configurations yield the following:

Access to fetch at 'https://us-central1-my-project.cloudfunctions.net/helloWorld' from origin 'http://127.0.0.1:5000' 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 didn’t change anything in the templated, auto generated Firebase code without the things I stated.

What am I missing?

Advertisement

Answer

You are actually mixing up HTTP Cloud Functions and Callable Cloud Functions.

Your helloWorld Cloud Function code corresponds to an HTTP one but the code in your front-end (i.e. public/index.html) calls a Callable one.

You should call the helloWorld Cloud Function as a REST API, i.e. with fetch or Axios, for example.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement