0

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.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Michel
  • 10,303
  • 17
  • 82
  • 179
  • Please add screenshots of your browser's Network tab showing the relevant requests and responses. – jub0bs Mar 24 '22 at 08:12
  • This is kind of long. Which part exactly should I look at? I see only one red line reading: us-central1-myapp.cloudfunctions.net myCloudFunction bundle.js (xhr) CORS missing Allow Origin – Michel Mar 24 '22 at 08:39
  • The actual request and the preflight request, as well as the response to the latter. – jub0bs Mar 24 '22 at 08:43
  • OK. Let me try to find that. Do you know how the lines you need are supposed to start? Just to give me a hint, since I am not used to to search for this kind of info. – Michel Mar 24 '22 at 08:54
  • 1
    The HTTP 408 code suggests that your function isn't properly handling the closing of the connection. I don't see any `resp.end()`, `resp.send()`, `resp.json()` or `res.redirect()` calls here, especially in the catch handler that should be checking `resp.headersSent` and sending back a HTTP 500 if it hasn't been closed off properly. – samthecodingman Mar 24 '22 at 09:21

0 Answers0