由于 CORS 限制,无法使用 firebase 在本地进行测试 [英] Unable to test locally using firebase due to CORS restriction

查看:20
本文介绍了由于 CORS 限制,无法使用 firebase 在本地进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的用例很简单,我只需要向我在本地开发的云功能发出一个 post 请求.

My current usecase is simple, I just need to make a post request to a cloud function I have locally developed.

关键是,当我开火时

firebase serve

主机部署在 localhost:5000

云功能部署在localhost:5001

这两者来自不同的来源,因为端口不同.因此,当浏览器发送初始预检请求时,它会失败并显示错误消息

These both are from different origin as port is different. Thus, when the browser sends the initial preflight request, it fails with error message

Failed to load http://localhost:5001/projectname/region/sendEnquiry: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.

如何设置标头以在本地进行测试?(再次,我不是专业人士,我猜当我决定在生产中部署时我将具有相同的来源.如果没有,无论如何我仍然需要解决方案)

How can I set the headers for testing this locally?(Again here I am not a pro, I am guessing I will have same origin when I decide to deploy in production. If not, anyways I will still need the solution)

谢谢.

推荐答案

Google 会限制某些调用,但您可以为您的 firebase 项目配置 CORS.通过非常混乱的文档很难找到如何做到这一点,我花了一段时间才找到正确的方法.

Google restricts certain calls but you can configure CORS for your firebase projects. It's hard to find how to do this by means of the very confusing docs, took me a while to find the right way.

请按照以下步骤操作:

  1. 转到 console.cloud.google.com
  2. 在左上角,选择您的 Firebase 项目
  3. 点击左上角的终端图标(看起来像>_)
  4. 在打开的终端中,点击三点图标并选择上传文件"
  5. 上传名为 cors.json 的文件,其内容如下:

[
 {
   "origin": ["*"],
   "method": ["GET"],
   "maxAgeSeconds": 3600
 }
]

  1. 在终端中,运行以下命令:gsutil cors set cors.json gs://yourbucketname.appspot.com(更改网址)
  1. In the terminal, run the following command: gsutil cors set cors.json gs://yourbucketname.appspot.com (change the url)

这允许来自其他来源的任何 GET 请求.

This allows any GET requests from other origins.

这篇关于由于 CORS 限制,无法使用 firebase 在本地进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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