简体   繁体   English

CORS BLOCKED 'Access-Control-Allow-Origin' Firebase 功能不允许

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

I had an error when sending data to a firebase database:firebase数据库发送数据时出错:

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.从来源“ http://localhost:3030 ”访问“ https://us-central1-pwagram-f39a5.cloudfunctions.net/storePostData ”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”header。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源

I had this issue when changing the end point using cors after deploying to firebase .在部署到cors后更改终点时,我遇到了这个问题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首先,我运行: npm install firebase-admin cors --save

Here is my package.json on folder firebase functions:这是我在文件夹firebase上的firebase函数:

{
  "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:这是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});
        });
 });
});

Here is my sw.js function that uses the function firebase , but is not working:这是我的sw.js function,它使用 function 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);
              });
          }

        })
    );
  }
});

When I change https://myFirebaseFUnctionLink/storePostData with normal firebase database link .json its work fine.当我用正常的 firebase 数据库链接.json更改https://myFirebaseFUnctionLink/storePostData时,它的工作正常。

This error occurs in the firebase function:这个错误出现在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)

I had the same problem.我有同样的问题。 The point is the syntax of the cors method.重点是 cors 方法的语法。 It takes 3 arguments: req, res, a function它需要 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, }); }); });

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.我使用 gsutil 更新了我的存储 cors.json 设置,我将云控制台中的单个函数权限更新为“允许未经身份验证”,我什至在 index.ts 中将 cors 标头添加到我的函数响应中——这些都没有帮助。

The solution : My firebase application needed billing enabled / upgraded to Blaze plan.解决方案:我的 firebase 应用程序需要启用计费/升级到 Blaze 计划。 This solved it immediately.这立即解决了它。

I had the same problem, you have to go in ".eslintrc.json" in "functions" folder and comment or remove this line:我有同样的问题,你必须进入“functions”文件夹中的“.eslintrc.json”并评论或删除这一行:

"promise/always-return": 2,

after that, you don't need to always add return in then blocks so remove the return keywords there like this:之后,您不需要总是在 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 });
            });
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS 对 XMLHttpRequest 的访问已被 CORS 策略阻止:No 'Access-Control-Allow-Origin' header - AWS Access to XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header CORS 策略已阻止访问“来自原点”的获取:请求的资源上不存在“Access-Control-Allow-Origin”header - Access to fetch at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 政策阻止了获取“url”的访问:请求的资源上不存在“Access-Control-Allow-Origin”header。 ReactJS - Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS 'Access-Control-Allow-Origin' CORS 尝试执行时 firebase function - 'Access-Control-Allow-Origin' CORS when trying to execute firebase function CORS on Azure Web App 返回错误:No 'Access-Control-Allow-Origin - CORS on Azure Web App returning error: No 'Access-Control-Allow-Origin 为什么 Google Cloud Storage 总是回答 cors 错误:请求的资源上不存在“Access-Control-Allow-Origin”header - Why is Google Cloud Storage always answering with cors error: No 'Access-Control-Allow-Origin' header is present on the requested resource 为什么在访问 AWS S3 存储桶时出现“CORS header 'Access-Control-Allow-Origin' missing”错误? - Why am I having the "CORS header ‘Access-Control-Allow-Origin’ missing" error when accessing an AWS S3 bucket? Localhost 到 AWS Lambda 没有 'Access-Control-Allow-Origin' Header - Localhost to AWS Lambda No 'Access-Control-Allow-Origin' Header Cors 请求被阻止 Firebase 功能 - Cors Request Blocked Firebase Functions 由于“Access-Control-Allow-Origin”,无法从 React 应用程序的 docker 容器中获取 API - Cannot fetch from API inside docker container from react app due to 'Access-Control-Allow-Origin'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM