【问题标题】:How can I GET from a Cloud Function from a Deployed Firebase App如何从已部署的 Firebase 应用程序的云函数中获取
【发布时间】:2019-07-21 06:32:51
【问题描述】:

当我使用 localhost:5001 调用函数时,我目前有一个可以在本地运行的 Firebase 应用程序;但是,当我尝试在直接路由时使用云功能时,我得到错误:禁止,当我尝试直接从我部署的 Firebase 应用程序中获取时,我得到一个 CORS 错误。

前端调用一个服务,从后端获取数据。

 const requestOptions = {
        method: 'GET',
        mode: 'cors',
        headers: new Headers({ 'Content-Type': 'application/json' })
    };
 return fetch("https://us-central1-polling-269dc.cloudfunctions.net/api/polls/get", requestOptions).then(handleResponse);

我也试过没有模式和标题,但它不起作用。 Fetch 被正确调用,但在 https://polling-269dc.firebaseapp.com/#/ 的加载页面上我收到以下错误消息:

CORS 策略阻止了从源“https://us-central1-polling-269dc.cloudfunctions.net/api/polls/get”获取“https://us-central1-polling-269dc.cloudfunctions.net/api/polls/get”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

在我的 index.js 的函数文件夹中,这是函数和先决条件导入:

const functions = require('firebase-functions');
const express = require('express');
const app = express();
const fire = require("./fire.js");
var database = fire.database();
var auth = fire.auth();

app.get("api/polls/get/", (req, res) => {
  var ref = database.ref("polls/");
  var query = ref.orderByChild("question");
  var sum = [];
  query.once("value", (snap) => {
    snap.forEach( (childSnap)  => {
      sum.push(childSnap.val());
    });
    res.json(sum);
  });
});

我也试过了

app.get("https://us-central1-polling-269dc.cloudfunctions.net/api/polls/get/", (req, res) => {

结果相似。我怀疑我调用了错误的 URL 或者我需要准备一些东西,但我找不到有关它的信息。

这是我的 firebase.json,这里可能有问题吗?

{
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "client/build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [ {
      "source": "**",
      "function": "app"
    } ]
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ]
  }
}

再次,当我使用 localhost 并使用 firebase 服务时,这可以工作,但我正在尝试为 Firebase 在线部署解决这个问题。提前致谢。

【问题讨论】:

    标签: javascript firebase cors google-cloud-functions firebase-hosting


    【解决方案1】:

    好的,所以我找到了问题所在;您需要在调用中添加导出的函数集的名称。我的电话应该是:

    https://us-central1-polling-269dc.cloudfunctions.net/app/api/polls/get
    

    而不是

    https://us-central1-polling-269dc.cloudfunctions.net/api/polls/get 
    

    我希望这对遇到类似问题的人有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      相关资源
      最近更新 更多