google-cloud-storage CORS 设置

google-cloud-storage CORS Setting

我已经把CORS设置到google云存储的bucket,没有Access-Control-Allow-Originheader

如果我的设置有误,希望你告诉我正确的方法。

我的设置

$ cat cors-json-file.json
[
  {
    "origin": [
      "*"
    ],
    "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type",     "Content-Length", "Accept-Encoding", "X-CSRF-Token"],
    "method": [
      "GET",
      "OPTIONS"
    ],
    "maxAgeSeconds": 1
  }
]

$ gsutil cors set cors-json-file.json gs://stone-swallow

$ gsutil cors get gs://stone-swallow
[{"origin": ["*"], "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token"], "method": ["GET", "OPTIONS"], "maxAgeSeconds": 1}]

尝试浏览器错误信息

var invocation = new XMLHttpRequest();
var url = 'http://storage.googleapis.com/stone-swallow/arcanine.png';

function callOtherDomain() {
  if(invocation) {
    invocation.open('GET', url, true);
    invocation.send();
  }
}
callOtherDomain();

XMLHttpRequest 无法加载 http://storage.googleapis.com/stone-swallow/arcanine.png. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' 因此不允许访问。

在您的 GET 方法中指定一个“来源”header。这应该可以解决问题。

确保存储桶上有 public-read:

$ gsutil -m acl set -R -a public-read gs://stone-swallow

我遇到了同样的问题,解决方案是在初始可恢复请求中添加一个 Header Origin: "https://ourapp.appspot.com"

但是,某些库,例如 sun.net.www.protocol.http.HttpURLConnection 不允许您更改 Origin header,因为以下变量:

restrictedHeaders = new String[]{"Access-Control-Request-Headers", "Access-Control-Request-Method", "Connection", "Content-Length", "Content-Transfer-Encoding", "Host", "Keep-Alive", "Origin", "Trailer", "Transfer-Encoding", "Upgrade", "Via"};

我的解决方法是使用允许更新 Origin header 的库创建一个新的 HttpRequest。我在我的案例中使用了 Okhttp(作为前 Android 开发者)。

OkHttpClient client = new OkHttpClient();
AppIdentityService appIdentityService = credential.getAppIdentityService();
Collection<String> scopes = credential.getScopes();
String accessToken = appIdentityService.getAccessToken(scopes).getAccessToken();
Request request = new Request.Builder()
        .url("https://www.googleapis.com/upload/storage/v1/b/" + bucket + "/o?name=" + fileName + "&uploadType=resumable")
        .post(RequestBody.create(MediaType.parse(mimeType), new byte[0]))
        .addHeader("X-Upload-Content-Type", mimeType)
        .addHeader("X-Upload-Content-Length", "" + length)
        .addHeader("Origin", "http://localhost:8080")
        .addHeader("Origin", "*")
        .addHeader("authorization", "Bearer "+accessToken)
        .build();
Response response = client.newCall(request).execute();
return response.header("location");

我有一个非常相似的问题,我花了几个小时才意识到我必须在我的 CORS 配置 json.

中将 responseHeader 设置为 `["*"]