Dealing with Access-Control-Allow-Origin in a Firebase cloud function

345 Views Asked by At

I have a cloud function working on Firebase. The code looks like this:

  import * as functions from "firebase-functions";
  import * as admin from "firebase-admin";
  import * as cors from "cors";
  import {Response} from "express";

  const corsHandler = cors();

  admin.initializeApp();
  ......

  exports.myCloudFunction = functions.https.onRequest(function(req, resp) {
    resp.set("Access-Control-Allow-Origin", "*");
    resp.set("Access-Control-Allow-Methods", "GET, POST");
    corsHandler(req, resp, async () => {
      const idToken = String(req.body.token);
      admin.auth().verifyIdToken(idToken)
          .then(function(decodedToken) {
            .... doing useful work irrelevant to the question ....
          }).catch(function(error) {
            // Handle error:
            functions.logger.log("Error in myCloudFunction,");
            functions.logger.log("\tauth().verifyIdToken:", error);
          });
    }); // End corsHandler.
  });

But when launching the app, after a little while I see in the web console this error message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myCloudFunction. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 408.

Didn't I set Access-Control-Allow-Origin inside myCloudFunction? Or did I do it incorrectly?

Any relevant help will be very much appreciated.

0

There are 0 best solutions below