Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable Cors for Firebase Cloud Functions

I am trying to enable cors for my http Cloud Functions. However, even when following this example that uses cors, when trying to fetch, it still gives me the error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my cloud function:

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

exports.foo = functions.https.onRequest((req, res) => {
    return cors(req, res, () => {
        let format = req.query.format;
        if (!format) {
            format = req.body.format;
        }

        //do stuff

    });
});

And here is how I fetch:

fetch("https://us-central1-my-database.cloudfunctions.net/foo", {
    method: "POST", 
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
}).then((res) => {
    // ...
}).catch((err) => {
    // ...
});

Why isn't cors working, and how can I fix it?

like image 719
yummypasta Avatar asked Mar 18 '18 17:03

yummypasta


People also ask

How do you call a Firebase cloud function?

The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app.

Does Firebase use HTTP requests?

Requests on your Firebase Hosting site can be proxied to specific HTTP functions. This also allows you to use your own custom domain with an HTTP function.


1 Answers

Try to use cors with its default parameters which are

{
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
}

In your case you just need to change a single line:

// code...

// const cors = require('cors')({origin: true});
const cors = require('cors')();

// code...
like image 82
ajorquera Avatar answered Nov 04 '22 12:11

ajorquera