CORS阻止了'Access-Control-Allow-Origin' Firebase函数不被允许。

6

我在向 firebase 数据库发送数据时出现了错误:

从来源 'http://localhost:3030' 访问 'https://us-central1-pwagram-f39a5.cloudfunctions.net/storePostData' 被 CORS 策略阻止:响应 preflight 请求无法通过访问控制检查:请求的资源上没有 'Access-Control-Allow-Origin' 标头。如果不透明响应符合您的需求,请将请求的模式设置为 'no-cors',以禁用 CORS 获取资源。

当我部署到 firebase 后,更改端点时,我遇到了这个问题。但仅在本地主机上运行时才会出现错误。由于我仍在使用它进行开发,因此需要使其在本地主机上工作。

首先,我输入命令:npm install firebase-admin cors --save

下面是文件夹 firebasepackage.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
}



这里是我所需的“cors”模块的 index.js 文件:
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});
        });
 });
});


这是使用firebase函数的sw.js函数,但没有工作:

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

        })
    );
  }
});

当我将https://myFirebaseFUnctionLink/storePostData更改为普通的firebase数据库链接.json时,它可以正常工作。

这个错误发生在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)

可能是重复的问题,参考此链接 https://dev59.com/5VgQ5IYBdhLWcg3wcjgs - Slava Rozhnev
仍然无法工作,抱歉。 - Ahmad Alfan Juniyanto
在我的项目中,我使用了 const cors = require('cors')({ origin: "*", credentials: true, methods: "GET" }); 这段代码对我很有效。 - Slava Rozhnev
1
我应该在哪里使用 const cors = require('cors')({ origin: "*", credentials: true, methods: "GET" }); - Ahmad Alfan Juniyanto
你应该在index.js的开头添加这个需求。 - Slava Rozhnev
2个回答

1

我也遇到了这个问题,错误提示完全一样。我使用 gsutil 更新了存储 cors.json 设置,在云控制台中更新了各个函数的权限为“允许未经身份验证”,甚至在 index.ts 中将 cors 标头添加到函数响应中 - 这些都没有帮助。

解决方案:我的 Firebase 应用需要启用计费/升级到 Blaze 计划。这立即解决了问题。


0

我曾经遇到过同样的问题。问题出在 cors 方法的语法上。它需要三个参数: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,
                });
            });
    });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接