Jbbae
Jbbae

Reputation: 1028

Firebase Cloud Functions - onCall not working

I'm testing a very simple implementation as described on FB docs (https://firebase.google.com/docs/functions/callable), and it's not working.

Here's my Firebase Function, deployed to cloud:

exports.getRecSkills = functions.https.onCall((data, context) => {
  return {text: data.text};
});

...and my client call (after initializing FB):

var getRecSkills = firebase.functions().httpsCallable('getRecSkills');

getRecSkills({text: '123'}).then(function(result) {
  console.log(result);
}).catch(function(error) {
  console.log(error.code);
  console.log(error.message);
});

I get a CORS header related issue but in the docs, it doesn't mention the need for CORS... am I missing something?

enter image description here

Some notes:

Been struggling with this for quite some time... Please help!

Upvotes: 10

Views: 3050

Answers (3)

Antonio Ooi
Antonio Ooi

Reputation: 1828

To get rid of your CORS error, make sure your firebase.json has the following headers:

"hosting": [
    {
      "headers": [
        {
          "source": "**",
          "headers": [
            {
              "key": "Access-Control-Allow-Origin",
              "value": "*"
            }
          ]
        }
      ]
   }
]

If you're running on Firebase Emulator on local device, make sure you have the following after initializing your Firebase Functions, otherwise your local device will still be calling the remote the Firebase Function and you'll hit the CORS error again:

if (window.location.hostname === "localhost") {
    console.log("localhost detected!");
    firebase.functions().useFunctionsEmulator('http://localhost:5001');
};

Upvotes: 2

Radu Linu
Radu Linu

Reputation: 1261

If you have CORS issues and you are using express in order to expose the API functions you have to allow cors:

import * as cors from 'cors';
import * as express from 'express';

const corsHandler = cors({origin: true});

const app = express();
app.use(corsHandler);

app.post('/createUser', async (request, response) => {
  await createUser(request, response);
});

exports.api = functions.https.onRequest(app);

Upvotes: 0

Kwabena Boohene
Kwabena Boohene

Reputation: 21

I had the same problem just recently but solved it after including my "projectId" in my config object. Below is a code snippet of the Firebase config object for Javascript. Make sure all fields have been filled in your config object and it should solve your undefined issue.

     var config = {
     apiKey: "<API_KEY>",
     authDomain: "<PROJECT_ID>.firebaseapp.com",
     databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
     projectId: "<PROJECT_ID>",
     storageBucket: "<BUCKET>.appspot.com",
     messagingSenderId: "<SENDER_ID>",
     };

Upvotes: 2

Related Questions