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?
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With