在 Cloud Functions for Firebase 中启用 CORS

编程入门 行业动态 更新时间:2024-10-11 09:21:39
本文介绍了在 Cloud Functions for Firebase 中启用 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在学习如何为 Firebase 使用新的 Cloud Functions,我遇到的问题是我无法访问通过 AJAX 请求编写的函数.我收到无 'Access-Control-Allow-Origin'"错误.这是我写的函数的一个例子:

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'}); })

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

Firebase 文档建议在函数中添加 CORS 中间件,我已经尝试过,但它对我不起作用:firebase.google/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: firebase.google/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:

  • 带日期格式的时间服务器
  • HTTPS 端点需要身份验证

第二个示例使用与您当前使用的不同的 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 for Firebase 中启用 CORS

本文发布于:2023-10-30 04:53:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Functions   Cloud   CORS   Firebase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!