【问题标题】:gs://<your-cloud-storage-bucket> has no CORS configurationgs://<your-cloud-storage-bucket> 没有 CORS 配置
【发布时间】:2017-11-22 04:19:49
【问题描述】:

我正在尝试在按钮单击事件时从我的 firebase 存储下载文件,但它给了我“Access-Control-Allow-Origin”错误。

https://firebase.google.com/docs/storage/web/download-files

根据上面的链接,我正在尝试配置 CORS。我安装了 gsutil 命令行工具。但我找不到需要复制此代码的 cors.json 文件

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

然后我使用命令gsutil cors get gs://&lt;your-cloud-storage-bucket&gt; 返回gsutil cors get gs://&lt;your-cloud-storage-bucket&gt;/ has no CORS configuration

我需要先为我的存储桶创建 CORS 配置文件吗?

以下是我的按钮点击方法,以防错误在代码中。

downloadAttachment(fileName) {
var uid = AuthService.uid;
let storageRef = firebase.storage().ref().child('assignments/' + uid + '/' + fileName);
storageRef.getDownloadURL().then(url => {
  console.log(url);
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function (event) {
    var blob = xhr.response;
  };
  xhr.open('GET', url);
  xhr.send();
});
}

错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:4200' 因此不允许访问。

谢谢。

【问题讨论】:

    标签: firebase cors firebase-storage


    【解决方案1】:

    是的,创建一个您想要的任何名称的文件(如果您愿意,可以将其命名为 cors.json)并将您喜欢的 CORS 配置设置放入其中,然后在其上运行 gsutil,如下所示:

    gsutil cors set cors.json gs://<your-cloud-storage-bucket>/
    

    这会将这些 CORS 配置设置上传到您的存储桶,然后您可以随时使用 gsutil cors get gs://&lt;your-cloud-storage-bucket&gt; 检索当前设置。

    【讨论】:

    • 我应该把这个cors.json文件保存在哪里?
    • 调用 gsutil 后,您不一定需要将 cors.json 文件保存在任何地方。您可以根据需要将其保存在您的 PC 上,例如,保存在您 PC 上的主目录中。但无论如何,一旦你第一次使用它运行“​​gsutil cors set”,之后你可以随时使用“gsutil cors get”获取当前的 CORS 配置设置。因此,如果您想稍后再次修改或添加设置,您只需获取 'gsutil cors get' 的输出,将其复制到一个新文件,添加您的更改,然后在该新文件上调用 'gsutil cors set'。
    • 我使用了这个命令gsutil cors set cors-json-file C:\Users\Prashant\AppData\Local\Google\Cloud SDK\cors.json。它返回CommandException: "cors" command does not support "file://" URLs. Did you mean to use a gs:// URL?
    • 您使用了错误的命令语法。您不需要“cors-json-file”部分。你只需要给它一个实际的文件名和你的存储桶 'gs:///' ,看起来你根本没有这样做。请在答案中使用命令语法。因此,'gsutil cors set C:\Users\Prashant\AppData\Local\Google\Cloud SDK\cors.json gs:///'。或者,只需更改到 'C:\Users\Prashant\AppData\Local\Google\Cloud SDK\' 目录并简单地运行 'gsutil cors set cors.json gs:///' .
    • 如果 storagebucket 的 url 中没有“gs://”怎么办。新版本中的配置没有“gs://”……如果我尝试去 gsutil cors set cors.json my_url_for_storage_bucket 它不起作用。
    【解决方案2】:

    只需运行命令

    gsutil cors set cors.json gs://<your-cloud-storage-bucket>
    

    来自包含 cors.json 文件的目录。

    【讨论】:

    • 投反对票,因为这与四年前给出的答案相同。
    猜你喜欢
    • 2022-01-19
    • 2020-11-05
    • 2017-10-03
    • 2016-10-28
    • 2019-08-16
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多