javascript - 在 Cloud Functions for Firebase 中启用 CORS

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

我目前正在学习如何使用新的 Cloud Functions for Firebase,我遇到的问题是我无法访问我通过 AJAX 请求编写的函数。我收到“无‘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'});
   })
})

我做错了什么?我将不胜感激。

更新:

Doug Stevenson的回答有帮助。添加 ({origin: true}) 解决了这个问题,我还必须将 response.status(500) 更改为 response.status(200) 一开始我完全错过了。

最佳答案

有两个sample functions由 Firebase 团队提供,演示了 CORS 的使用:

第二个示例使用与您当前使用的不同的方式处理 cors。

考虑像这样导入,如示例所示:

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

函数的一般形式如下:

exports.fn = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        // your function body here - use the provided req and res from cors
    })
});

关于javascript - 在 Cloud Functions for Firebase 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755131/

相关文章:

javascript - 如何为每个 Jasmine 测试重置 Knockout?

javascript - Rails 3 和 plupload - 上传后如何进行重定向?

Javascript 函数不修改数组(引用?)

javascript - Windows 商店应用程序 - 元素背景颜色

iOS Swift Firebase InstanceID token 第一次返回 Nil

curl - 使用 cURL 使用 JSON key 文件进行 Google Cloud 身份验证

c# - 如何使用 json 作为身份验证创建 TranslationServiceClient?

firebase - 在 Firebase 安全规则中,您如何阻止黑客运行脚本来注册您的网站?请记住,我需要他们能够注册

angularjs - 将 (es6) firebase 3 npm 模块导入 Angular 时遇到问题

python-3.x - 谷歌云存储、计算引擎和权限不足错误