我目前正在学习如何使用Firebase的新云函数,我遇到的问题是我无法访问我通过AJAX请求编写的函数。我得到了“No 'Access-Control-Allow-Origin'”错误。下面是我写的函数示例:

exports.test = functions.https.onRequest((request, response) => {
  response.status(500).send({test: 'Testing functions'});
})

函数位于这个url中: https://us-central1-fba-shipper-140ae.cloudfunctions.net/test

Firebase文档建议在函数中添加CORS中间件,我尝试过,但对我不起作用:https://firebase.google.com/docs/functions/http-events

我是这样做的:

var cors = require('cors');    

exports.test = functions.https.onRequest((request, response) => {
   cors(request, response, () => {
     response.status(500).send({test: 'Testing functions'});
   })
})

我做错了什么?如果你能帮我,我会很感激。

更新:

道格·史蒂文森的回答很有帮助。添加({origin: true})修复了这个问题,我还必须将response.status(500)更改为response.status(200),这是我一开始完全错过的。


当前回答

没有CORS解决方案对我有效…直到现在!

Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...

dr -如果没有CORS解决方案工作,检查您的firebase函数日志并调试任何错误

其他回答

请参阅下面我如何设置我的快车与CORS。

“https://pericope。app'是我的Firebase项目的自定义域。

看起来所有其他答案都推荐起源:true或*。

我很犹豫是否允许所有的起源,因为它将允许任何人访问api。如果您正在创建一个公共服务,这是没问题的,但如果您正在使用您的数据做任何事情,这都是有风险的,因为它是一个特权环境。例如,这个管理SDK绕过您为Firestore或Storage设置的任何安全规则。

//Express
const express = require('express');
const app = express();

const cors = require('cors');
app.use(cors({
  origin: 'https://pericope.app'
}));

我刚刚发表了一篇关于这方面的文章:

https://mhaligowski.github.io/blog/2017/03/10/cors-in-cloud-functions.html

通常,您应该使用Express CORS包,它需要一些hack才能满足GCF/Firebase Functions中的要求。

希望有帮助!

我对安德烈自己的问题有一些补充。

看起来你不需要在cors(req, res, cb)函数中调用回调,所以你可以在函数的顶部调用cors模块,而不需要在回调中嵌入你的所有代码。如果您想随后实现cors,这将更快。

exports.exampleFunction = functions.https.onRequest((request, response) => {
    cors(request, response, () => {});
    return response.send("Hello from Firebase!");
});

不要忘记初始化cors,就像开头提到的那样:

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

更新:任何需要时间的响应函数都有可能在此实现中出现CORS错误,因为它没有适当的async/await。不要在返回静态数据的快速原型端点之外使用。

对于它的价值,我有同样的问题,当传递应用程序到onRequest。我意识到问题在于firebase函数的请求url上的末尾斜杠。Express正在寻找'/',但我在函数[project-id].cloudfunctions.net/[function-name]上没有后面的斜杠。CORS的错误是假阴性。当我添加后面的斜杠时,我得到了我所期待的响应。

补充我的经验。 我花了几个小时试图找到为什么我有CORS错误。

碰巧我重命名了我的云功能(这是我在一次大升级后尝试的第一次)。

因此,当我的firebase应用程序使用错误的名称调用云函数时,它应该抛出404错误,而不是CORS错误。

修复我的firebase应用程序中的云函数名称修复了这个问题。

我在这里填了一份关于这个的错误报告 https://firebase.google.com/support/troubleshooter/report/bugs