使用从本地主机上传到GCS时发生CORS错误

时间:2018-11-20 01:23:13

标签: cors xmlhttprequest google-cloud-storage

PUT设置为Content-Type时,通过image/png请求从本地主机将文件上传到GCS signed url时遇到了CORS错误:

Access to XMLHttpRequest at 'https://storage.googleapis.com/{{BUCKET_NAME}}/folder/image.png?Expires=1542676226&GoogleAccessId=XXXX&Signature=YYYY' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

出于开发目的,我确保将存储桶的CORS策略设置得尽可能宽松:

$ gsutil cors get gs://{{BUCKET_NAME}}

[
    {
      "origin": ["*"], // also tried "http://localhost:3000"
      "method": ["*"],
      "responseHeader": ["*"]
    }
]

很遗憾,我没有收到403以外的任何东西。

2 个答案:

答案 0 :(得分:0)

我花了一个小时来解决这个问题,终于意识到content-type是强制性的,它必须与您要上传的文件的内容类型匹配。

https://cloud.google.com/storage/docs/access-control/signing-urls-manually

在文件上设置了正确的MIME类型后,上传成功。

我过去使用一个库来获取文件的正确MIME类型: https://www.npmjs.com/package/mime-types

答案 1 :(得分:0)

对于我来说,我使用nodejs + "@google-cloud/storage": "^3.0.2"

创建签名的URL时,密钥为version。默认版本为v2

      const getSignedUrlResponse: GetSignedUrlResponse = await file.getSignedUrl({
        action: 'write',
        expires: Date.now() + 60 * 1000
        // version: 'v4'
      });

对于客户端,我使用fetch API,这是代码段:

fetch(signedUrl, { method: 'PUT', body: file })

在Chrome控制台中出现如下所示的403 cors错误:

  

输入https://storage.googleapis.com/ez2on/adminUsers.png?GoogleAccessId=cloud-storage-admin%40shadowsocks-218808.iam.gserviceaccount.com&Expires=1562832855&Signature=cllvUH%2FaOxKHDy4GNPcI1FP1BMqbYir08NYFQtxTJ5lpbWBmHkfUgAFx2xfmHjDrzbaIJJ9L8Jntld0YnVIC%2FTHjo3qQC3YNQtr%2B8Jr%2BnT8QuyhAQXBtWAfyvnEfmidF1z0Lz870IiPcgfR2DXDi6XXS1uTVDpasa71O4nttnMR2rzAaB6Ev9IkoxPvZ49dyxjbOOp2aFAHEE9LehHZNRwaRqBl2JJN7rHHtXol%2B%2B8loEu99D3dqj5Ph12Lh7%2BNREG0NarZKZx0Iagw6hW%2BW5rKOCuGyuablvaqgntHpD2WIs2qLCGtU8B1rLhyd4ds5%2F7lHz2AcAZD09uNz%2BKG%2BUA%3D%3D 403

     

通过CORS策略阻止从原点“ https://storage.googleapis.com/ez2on/adminUsers.png?GoogleAccessId=cloud-storage-admin%40shadowsocks-218808.iam.gserviceaccount.com&Expires=1562832855&Signature=cllvUH%2FaOxKHDy4GNPcI1FP1BMqbYir08NYFQtxTJ5lpbWBmHkfUgAFx2xfmHjDrzbaIJJ9L8Jntld0YnVIC%2FTHjo3qQC3YNQtr%2B8Jr%2BnT8QuyhAQXBtWAfyvnEfmidF1z0Lz870IiPcgfR2DXDi6XXS1uTVDpasa71O4nttnMR2rzAaB6Ev9IkoxPvZ49dyxjbOOp2aFAHEE9LehHZNRwaRqBl2JJN7rHHtXol%2B%2B8loEu99D3dqj5Ph12Lh7%2BNREG0NarZKZx0Iagw6hW%2BW5rKOCuGyuablvaqgntHpD2WIs2qLCGtU8B1rLhyd4ds5%2F7lHz2AcAZD09uNz%2BKG%2BUA%3D%3D”到“ http://localhost:3000”的访存:所请求的资源上没有“ Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”以在禁用CORS的情况下获取资源。

versionv2更改为v4之后:

      const getSignedUrlResponse: GetSignedUrlResponse = await file.getSignedUrl({
        action: 'write',
        expires: Date.now() + 60 * 1000,
        version: 'v4'
      });

错误消失了。

enter image description here