0

Setting up a firestore functions.https.onRequest, calling this on my frontend errors No 'Access-Control-Allow-Origin' header is present on the requested resource.

Tried a lot of other answers but could not get it to work. how do I set cors up properly for google cloud functions?

I tried most of the answers on stackoverflow the past 3 hours.

This is my attempt using cors middleware

const functions = require('firebase-functions');
const cors = require('cors')({
  origin: true
});

const admin = require('firebase-admin');

admin.initializeApp();


exports.exampleFunction = functions.https.onRequest(async (req, res) => {

  return cors(req, res, () => {

    // Forbidding PUT requests.
    if (req.method === 'PUT') {
      return res.status(403).send('Forbidden!');
    }

    //respond to CORS preflight requests
    if (req.method == 'OPTIONS') {
      res.status(204).send('');
      return null
    }

   // code ...
   res.sendStatus(200);
}

I dont know what I am doing wrong.

What am I doing wrong here?

moritz
  • 366
  • 3
  • 17
  • I'm confused -- you say you're trying to set up CORS on a Cloud Function but you're referencing a bucket and Cloud Storage URLs. Which is it? Using the [cors middleware](https://expressjs.com/en/resources/middleware/cors.html) has worked for me and should be able to work for you as well, just read how to configure it. – Michael Bleigh Aug 28 '19 at 17:00
  • I am also confused. So I thought that the Cloud Function is referenced in the CloudStorageBucket (as there is a project with the same name as my firebase project). Will try again using cors middleware in the cloud function. Thanks! Please see my updated question, I am now using the cors middleware like in the sample function, but still get the error. – moritz Aug 29 '19 at 09:49

2 Answers2

0

Use URL Rewrites to allow the function to be served under your domain

Okay, the proper solution to this is to rewrite the function to use the domain name and therefore we do not even need cors.

under the hosting section in firebase.json add the following to the beginning of the "rewrites": section.

  {
    "source": "/api/functionName/**",
    "function": "functionName"
  },

And I called the request via:

// send data to cloudfunction
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://example.com/api/functionName/?param1="+ this.param1, true);
xhr.send();

This allows to get the param in the cloud function via req.query.param1

moritz
  • 366
  • 3
  • 17
-2

You mentioned getting this error in the front end - have you disabled CORS in chrome to allow for the requests to go through?

link: https://alfilatov.com/posts/run-chrome-without-cors/

Flignats
  • 1,234
  • 10
  • 21