Fail to call firebase 'onCall' function in front end due to CORS policy

Viewed 913

I am trying to write a function which can get the data from database of Firebase. So I wrote the following simple function to see if I can call him on the front-end page.
But I received the error message :

Access to fetch at 'https://us-central1-undefined.cloudfunctions.net/sayHello' from origin 'http://localhost:8081' 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.

Code in 'index.js':

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


exports.sayHello = functions.https.onCall((data, context) => {
  const name = data.name;
  return `hello ${name} :)`.then(()=>{
    console.log('success');
  }).catch((err)=>{console.log(err)})
});

Code in the component which calls the function:

import { db, functions, rootRef } from '../db/firebaseConfig.js';

methods: {
  sayHello(){
    const sayHello = functions.httpsCallable('sayHello');
    // call the function and pass data
    sayHello({ name: 'Peter' }).then(result => {
        console.log(result);
     });
  },

I have also read the answer Enabling CORS in Cloud Functions for Firebase. But it doesn't work for me.

1 Answers

Do you use the functions emulator? If so you need to set it like so

firebase.initializeApp(config)
firebase.functions().useFunctionsEmulator("http://localhost:5001")

(Change 5001 port to the port you use)

Related