yummypasta
yummypasta

Reputation: 1468

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?

Upvotes: 8

Views: 5682

Answers (1)

ajorquera
ajorquera

Reputation: 1309

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...

Upvotes: 1

Related Questions