google-cloud-storage CORS设置

时间:2015-03-08 05:24:13

标签: google-cloud-storage

我已经完成了对谷歌云存储设备的CORS设置,没有Access-Control-Allow-Origin标头

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

我的设置

$ 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。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:8080”访问。

3 个答案:

答案 0 :(得分:3)

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

但是,某些图书馆,例如sun.net.www.protocol.http.HttpURLConnection,由于以下变量,您无法更改Origin标头:

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"};

我的解决方法是创建一个新的HttpRequest,其中包含一个允许更新Origin标头的库。我在我的案例中使用了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");

答案 1 :(得分:0)

在GET方法上指定“Origin”标题。这应该可以解决问题。

答案 2 :(得分:0)

确保存储桶上有公开读取:

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