'CORS BLOCKED 'Access-Control-Allow-Origin' Firebase Functions not allowed

I had an error when sending data to a firebase database :

Access to fetch at 'https://us-central1-pwagram-f39a5.cloudfunctions.net/storePostData' from origin 'http://localhost:3030' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

I had this issue when changing the end point using cors after deploying to firebase. But the there is only an error when running on localhost. I need this to work on localhost because I am still using it for development.

First, I run: npm install firebase-admin cors --save

Here is my package.json on folder firebase functions:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "firebase-admin": "^8.9.1",
    "firebase-functions": "^3.3.0"
  },
  "devDependencies": {
    "eslint": "^5.12.0",
    "eslint-plugin-promise": "^4.0.1",
    "firebase-functions-test": "^0.1.6"
  },
  "private": true
}


Here is index.js file i am require cors module:

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


exports.storePostData = functions.https.onRequest(function(request, response) {
 return cors(function(request, response) {

    admin.database().ref('posts').push({
        id: request.body.id,
        title: request.body.title,
        location: request.body.location,
        image: request.body.image
    })
        .then(function() {
            return response.status(201).json({message: 'Data stored', id:request.body.id});
        })
        .catch(function(err) {
           return response.status(500).json({error: err});
        });
 });
});

Here is my sw.js function that uses the function firebase, but is not working:

self.addEventListener('sync', function(event) {
  console.log('[Service Worker] Background syncing', event);
  if (event.tag === 'sync-new-posts') {
    console.log('[Service Worker] Syncing new Posts');
    event.waitUntil(
      readAllData('sync-posts')
        .then(function(data) {
          for (var dt of data) {
            fetch('https://myFirebaseFUnctionLink/storePostData', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
              },
              body: JSON.stringify({
                id: dt.id,
                title: dt.title,
                location: dt.location,
                image: 'https://myfirebaselink/'
              })
            })
              .then(function(res) {
                console.log('Sent data', res);
                if (res.ok) {
                  deleteItemFromData('sync-posts', dt.id); // Isn't working correctly!
                }
              })
              .catch(function(err) {
                console.log('Error while sending data', err);
              });
          }

        })
    );
  }
});

When I change https://myFirebaseFUnctionLink/storePostData with normal firebase database link .json its work fine.

This error occurs in the firebase function :

TypeError: Cannot read property 'origin' of undefined
    at /srv/node_modules/cors/lib/index.js:219:40
    at optionsCallback (/srv/node_modules/cors/lib/index.js:199:9)
    at corsMiddleware (/srv/node_modules/cors/lib/index.js:204:7)
    at /srv/index.js:9:9
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:49:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)


Solution 1:[1]

I had the same problem. The point is the syntax of the cors method. It takes 3 arguments: req, res, a function

return cors(req, res, function () {
        admin
            .database()
            .ref('posts')
            .push(req.body)
            .then(function () {
                return res.status(201).json({
                    message: 'Data stored',
                    id: req.body.id,
                });
            })
            .catch(function (err) {
                return res.status(500).json({
                    error: err,
                });
            });
    });

Solution 2:[2]

I ran into this problem as well, exact error wording. I updated my storage cors.json settings using gsutil, I updated the individual function permissions in the cloud console to "allow unauthenticated", and I even added the cors header to my function response in index.ts - none of those helped.

The solution: My firebase application needed billing enabled / upgraded to Blaze plan. This solved it immediately.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prostagm4
Solution 2 Chris Schertenlieb