Veröffentlicht am

Firebase – Express – Cors – Issue

When deploying a simple Express app to Firebase Cloud Functions (https), you need to avoid having your app stopped by CORS issues and not working properly. In this example, I wrote a very small Express backend to provide some json data and show how to solve the problem concerning CORS.

[...]

const references = require("./references.json");

app.get("/references", (req, res) => {
    res.send(references);
});

[...]

exports.app = functions.https.onRequest(app);

When the function is deployed, you can reach it e.g. under

https://firebase-region-appid-xxxxx.com/app

In another small React app, I use this backend to fetch the JSON:

[...]

const fetchUrl = 'https://firebase-region-appid-xxxxx.com/app/references'; 

fetch(fetchUrl, 
{
     "credentials": 'same-origin',
     "method": 'get',
     "headers": {
          "Authorization": 'Basic ' + authphrase 
      }
})

[...]

Without adding some code, the json file will not be provided as expected.

You need to setup CORS as middleware within the express api. Just like this

[...]

const references = require("./references.json");

const cors = require("cors");
app.use(cors({ origin: true }));

app.get("/references", (req, res) => {
    res.send(references);
});

[...]

exports.app = functions.https.onRequest(app);

That’s all folks..