我目前正在学习如何使用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),这是我一开始完全错过的。


当前回答

只有这种方式对我有效,因为我在我的请求中有授权:

exports.hello = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Credentials', 'true'); // vital
if (request.method === 'OPTIONS') {
    // Send response to OPTIONS requests
    response.set('Access-Control-Allow-Methods', 'GET');
    response.set('Access-Control-Allow-Headers', 'Content-Type');
    response.set('Access-Control-Max-Age', '3600');
    response.status(204).send('');
} else {
    const params = request.body;
    const html = 'some html';
    response.send(html)
} )};

其他回答

如果你在本地测试firebase应用程序,那么你需要将函数指向localhost而不是cloud。默认情况下,firebase服务或firebase模拟器:当你在你的web应用程序上使用它时,开始将函数指向服务器而不是localhost。

在firebase初始化脚本后的html头中添加以下脚本:

 <script>
      firebase.functions().useFunctionsEmulator('http://localhost:5001')
 </script> 

确保在将代码部署到服务器时删除此代码段。

我得到了错误,因为我调用了一个在客户端不存在的函数。例如:

firebase.functions().httpsCallable('makeSureThisStringIsCorrect');

Firebase v2的云功能

Firebase v2的云函数现在允许您直接在HTTP选项中配置cors。它的工作不需要任何第三方软件包:


import { https } from 'firebase-functions/v2';

export myfunction = https.onRequest({ cors: true }, async (req, res) => {
  // this will be invoked for any request, regardless of its origin
});

请注意:

在撰写本文时,v2正在公开预览中。 目前v2中只支持区域的一个子集。 函数名被限制为小写字母、数字和破折号。 你可以在一个代码库中同时使用v1和v2函数。为了提高可读性,请更新导入以分别访问firebase-functions/v1或firebase-functions/v2。

我是Firebase的初学者(30分钟前注册的)。我的问题是我调用了端点

https://xxxx-default-rtdb.firebaseio.com/myendpoint

而不是

https://xxxx-default-rtdb.firebaseio.com/myendpoint.json

如果您刚开始使用Firebase,请确保不要忘记.json扩展名。

通过“*”改变true对我来说很有用,所以它看起来是这样的:

const cors = require('cors')({ origin: "*" })

我尝试了这种方法,因为在一般情况下,这是响应头的设置方式:

'Access-Control-Allow-Origin', '*'

请注意,这将允许任何域调用您的端点,因此它是不安全的。

此外,你可以阅读更多关于文档的内容: https://github.com/expressjs/cors