The functions I have created is working fine in local using firebase serve command. When I deployed it to firebase functions it started to throw error:
"Access to XMLHttpRequest at 'https://us-central1-mysample.cloudfunctions.net/api/configSettings' from origin 'https://mysample.web.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"
Below are the key points about the project & code:
- Using ExpressJs for web API creation
- Both Hosting and Functions are inside same Firebase project only
- I have tried below CORS npm package implementation
const cors = require('cors')
var corsOptionsDelegate = function (req, callback) {
console.log("req.header('Origin') : ", req.header('Origin'))
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS
response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.options('*', cors(corsOptionsDelegate));
- Also I have tried with below way:
app.use((req, res, next) => {
const allowedOrigins = ['https://mysample.web.app', 'https://mysample.firebase.webapp'];
const origin = req.headers.origin;
console.log("origin : ", origin)
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', true);
return next();
});
But none of the way resolved my issue. Is there any setting I have to in Firebase portal ? Any help.