【问题标题】:How to add CORS to firebase - Access-Control-Allow-Origin如何将 CORS 添加到 Firebase - Access-Control-Allow-Origin
【发布时间】:2020-01-01 21:49:24
【问题描述】:

设置 Firestore 函数。https.onRequest,在我的前端错误中调用它请求的资源上不存在“Access-Control-Allow-Origin”标头。

尝试了很多其他答案,但无法使其正常工作。如何为谷歌云功能正确设置 cors?

在过去的 3 个小时里,我在 stackoverflow 上尝试了大部分答案。

这是我使用 cors 中间件的尝试

const functions = require('firebase-functions');
const cors = require('cors')({
  origin: true
});

const admin = require('firebase-admin');

admin.initializeApp();


exports.exampleFunction = functions.https.onRequest(async (req, res) => {

  return cors(req, res, () => {

    // Forbidding PUT requests.
    if (req.method === 'PUT') {
      return res.status(403).send('Forbidden!');
    }

    //respond to CORS preflight requests
    if (req.method == 'OPTIONS') {
      res.status(204).send('');
      return null
    }

   // code ...
   res.sendStatus(200);
}

我不知道我做错了什么。

我在这里做错了什么?

【问题讨论】:

  • 我很困惑——您说您正在尝试在云函数上设置 CORS,但您引用的是存储桶和云存储 URL。它是哪一个?使用 cors middleware 对我有用,应该也可以为你工作,只需阅读如何配置它。
  • 我也很困惑。所以我认为CloudStorageBucket中引用了Cloud Function(因为有一个与我的firebase项目同名的项目)。将再次尝试在云功能中使用 cors 中间件。谢谢!请查看我更新的问题,我现在正在使用示例函数中的 cors 中间件,但仍然出现错误。

标签: firebase google-cloud-platform cors google-cloud-functions


【解决方案1】:

您提到在前端遇到此错误 - 您是否在 chrome 中禁用了 CORS 以允许请求通过?

链接:https://alfilatov.com/posts/run-chrome-without-cors/

【讨论】:

  • 对不起,但这不是我要找的。它需要在每个人的生产环境中工作。
【解决方案2】:

使用 URL 重写以允许在您的域下提供该功能

好的,解决这个问题的正确方法是重写函数以使用域名,因此我们甚至不需要 cors。

firebase.json 的托管部分下,将以下内容添加到"rewrites": 部分的开头。

  {
    "source": "/api/functionName/**",
    "function": "functionName"
  },

我通过以下方式调用了请求:

// send data to cloudfunction
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://example.com/api/functionName/?param1="+ this.param1, true);
xhr.send();

这允许通过req.query.param1获取云函数中的参数

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2019-02-07
    • 2016-06-10
    • 2011-06-27
    • 2020-05-05
    相关资源
    最近更新 更多