【问题标题】:CORS BLOCKED 'Access-Control-Allow-Origin' Firebase Functions not allowedCORS BLOCKED 'Access-Control-Allow-Origin' Firebase 功能不允许
【发布时间】:2020-05-05 01:03:13
【问题描述】:

firebase 数据库发送数据时出错:

从源“http://localhost:3030”获取“https://us-central1-pwagram-f39a5.cloudfunctions.net/storePostData”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源

我在部署到firebase 后使用cors 更改端点时遇到了这个问题。但是在本地主机上运行时只有一个错误。我需要它才能在 localhost 上工作,因为我仍在使用它进行开发。

首先,我运行:npm install firebase-admin cors --save

这是我在文件夹 firebase 上的 package.json 函数:

{
  "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
}


这是 index.js 文件,我需要 cors 模块:

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});
        });
 });
});

这是我的 sw.js 函数,它使用了函数 firebase,但不起作用:

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);
              });
          }

        })
    );
  }
});

当我使用正常的 firebase 数据库链接 .json 更改 https://myFirebaseFUnctionLink/storePostData 时,它工作正常。

这个错误出现在firebase函数中:

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)

【问题讨论】:

  • 还是不行,抱歉
  • 在我的项目中我使用了const cors = require('cors')({ origin: "*", credentials: true, methods: "GET" }); 它对我有用
  • 我应该在哪里使用const cors = require('cors')({ origin: "*", credentials: true, methods: "GET" });
  • 您应该在 index.js 开始时添加此要求

标签: javascript firebase cors grand-central-dispatch


【解决方案1】:

我遇到了同样的问题, 您必须进入“functions”文件夹中的“.eslintrc.json”并注释或删除此行:

"promise/always-return": 2,

之后,您不需要总是在 then 块中添加 return ,因此删除 return 关键字,如下所示:

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

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
const serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://you-project-addres.firebaseio.com/',
});

exports.storePostData = functions.https.onRequest((request, response) => {
    return cors(request, response, () => {
        admin
            .database()
            .ref('posts')
            .push({
                id: request.body.id,
                title: request.body.id,
                location: request.body.location,
                image: request.body.image,
            })
            .then(() => {
                response.status(201).json({ message: 'Data stored', id: request.body.id });
            })
            .catch((err) => {
                response.status(500).json({ error: err });
            });
    });
});

【讨论】:

  • 是什么让你认为这是 linter 的问题,或者 OP 甚至在他们的 .eslintrc.json 文件中有该条目?
【解决方案2】:

我遇到了同样的问题。重点是 cors 方法的语法。它需要 3 个参数:req、res、一个函数

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,
                });
            });
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-19
    • 2015-06-17
    • 2013-12-09
    • 2013-09-09
    • 2012-03-08
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多