3

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Alex Chen
  • 35
  • 4
  • 1
    Can you show how you have implemented the solution presented in the answer you mention (https://stackoverflow.com/a/42756623/3371862)? It is actually THE solution. – Renaud Tarnec Jun 04 '20 at 10:26
  • I added the code ```const cors = require('cors')({origin: true});``` and I updated the firebase functions to the latest version. – Alex Chen Jun 04 '20 at 10:58
  • Actually, I realise now that you are using a Callable Cloud Function, not an HTTPS one. See https://stackoverflow.com/questions/50278537/firebase-callable-function-cors – Renaud Tarnec Jun 04 '20 at 17:05

1 Answers1

1

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)

dowi
  • 1,005
  • 15
  • 30