如何从已部署的Firebase应用程序中获取云功能

时间:2019-02-27 13:57:38

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

我目前有一个Firebase应用程序,当我使用localhost:5001调用函数时,它可以在本地运行;但是,当我在直接路由时尝试使用云功能时,出现错误:FORBIDDEN,并且当我尝试从已部署的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);

我也尝试过只在上面没有模式和标题,但这是行不通的。提取已正确调用,但是在https://polling-269dc.firebaseapp.com/#/的加载页面上,我收到以下错误消息:

通过CORS策略阻止从原点“ https://us-central1-polling-269dc.cloudfunctions.net/api/polls/get”到“ https://polling-269dc.firebaseapp.com”的访存:所请求的资源上没有“ 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"
    ]
  }
}

同样,当我使用本地主机并使用firebase serve时,此方法有效,但我试图通过在线进行Firebase部署来解决。预先感谢。

1 个答案:

答案 0 :(得分:0)

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

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

代替

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

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

相关问题