在 Cloud Functions 中为 Firebase 启用 CORS [英] Enabling CORS in Cloud Functions for Firebase

查看:35
本文介绍了在 Cloud Functions 中为 Firebase 启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习如何为 Firebase 使用新的 Cloud Functions,但我遇到的问题是我无法访问我通过 AJAX 请求编写的函数.我收到没有'访问控制-允许-来源'"错误.这是我编写的函数示例:

I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:

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

该函数位于此网址中:https://us-central1-fba-shipper-140ae.cloudfunctions.net/test

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

Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: 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'});
   })
})

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

What am I doing wrong? I would appreciate any help with this.

更新:

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

Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500) to response.status(200) which I completely missed at first.

推荐答案

有两个示例函数 由 Firebase 团队提供,用于演示 CORS 的使用:

There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

第二个示例使用与您当前使用的不同的 cors 工作方式.

The second sample uses a different way of working with cors than you're currently using.

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

Consider importing like this, as shown in the samples:

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

你的函数的一般形式如下:

And the general form of your function will be like this:

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

这篇关于在 Cloud Functions 中为 Firebase 启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆