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


当前回答

在我的例子中,错误是由云函数调用者限制访问引起的。请将allUsers添加到云函数调用器。请抓住林克。更多信息请参考文章

其他回答

如果有像我这样的人:如果你想在同一个项目中调用云函数,你可以init firebase sdk并使用onCall方法。它会为你处理一切:

exports.newRequest = functions.https.onCall((data, context) => {
    console.log(`This is the received data: ${data}.`);
    return data;
})

像这样调用这个函数:

// Init the firebase SDK first    
const functions = firebase.functions();
const addMessage = functions.httpsCallable(`newRequest`);

Firebase文档:https://firebase.google.com/docs/functions/callable

如果你不能初始化SDK,以下是其他建议的精髓:

如果在默认位置使用firebase托管和主机,请选择“重写:https://firebase.google.com/docs/hosting/full-config#rewrites” 或者像krishnazden建议的那样使用CORS: https://stackoverflow.com/a/53845986/1293220

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

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

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

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

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

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

通过这么多的搜索,我可以在相同的firebase文档中找到这个解决方案,只是在路径中实现cors:

import * as express from "express";
import * as cors from "cors";


const api = express();
api.use(cors({ origin: true }));
api.get("/url", function);

链接firebase文档:https://firebase.google.com/docs/functions/http-events

一个额外的信息,只是为了那些在一段时间后谷歌这个:

如果你正在使用firebase托管,你也可以设置重写,例如一个url (firebase_hosting_host)/api/myfunction重定向到(firebase_cloudfunctions_host)/doStuff函数。这样,由于重定向是透明的并且是服务器端的,所以您不必处理cors。

你可以在firebase.json中设置一个重写部分:

"rewrites": [
        { "source": "/api/myFunction", "function": "doStuff" }
]

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

看起来你不需要在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。不要在返回静态数据的快速原型端点之外使用。