Create React App 中 httpsCallable firebase 上的 CORS 错误

IT技术 reactjs firebase cors google-cloud-functions create-react-app
2021-05-23 14:02:42

已解决 - 请参阅下面的答案。

可调用函数导致 CORS 错误,如下所示:

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

功能代码:

exports.createUser = functions.https.onCall((data, context) => {
    const email = data.email
    const password = data.password

    admin.auth().createUser({
        email: email,
        emailVerified: false,
        password: password
    }).then((res) => {
        return {
            response: res
        }
    }).catch((err) => {
        return {err}
    })

})

客户端:

    const handleAddUser = () => {
      let pswd = passwordGen(7)
      const createUser = firebase.functions().httpsCallable('createUser');
      createUser({email: email, password: pswd}).then(function(result) {
        let res = result.data
        console.log(res)
      }).catch(function(error) {
        console.log(error.code)
      })

    }

包.json

{
  "name": "careerhub-web",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "antd": "^4.0.2",
    "firebase": "^7.10.0",
    "node-sass": "^4.13.1",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-email-editor": "^1.0.0",
    "react-reveal": "^1.2.2",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "recharts": "^2.0.0-beta.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

即使我处于离线状态,此错误仍然存​​在。

我尝试过的事情:

  1. 更新 Firebase SDK
  2. 添加“代理”:'...' 到 package.json
  3. 使用云功能指南中的基本功能
  4. 删除firebase应用程序并删除功能并重新部署
  5. 添加const cors = require('cors')({origin: true});到功能
1个回答

事实证明,该错误是 Google 端关于 IAM 权限的一个记录不完整的更改,无法通过 Firebase 控制台清楚地访问这些更改。

原因:

云函数禁止访问该函数。新创建的函数没有 Cloud Functions Invoker。此更改已于 2020 年 1 月 15 日实施

解决方案:

创建 Cloud Functions Invoker 并设置为 allUsers。 https://cloud.google.com/functions/docs/securing/managing-access-iam