如何通过 CORS 使用从 Go API 返回的 SignedURL?
当前设置:
存储桶配置
gsutil cors 获取 gs://example-bucket
返回:
[{
"maxAgeSeconds": 1,
"method": ["GET", "HEAD", "PUT", "DELETE", "POST", "OPTIONS"],
"origin": ["http://example.com", "https://example.com", "http://localhost:4000"],
"responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token"
]}]
Go API 调用
acc, _ := appengine.ServiceAccount(ctx)
signedUrl, err := storage.SignedURL(
"example-bucket",
fileName,
&storage.SignedURLOptions{
GoogleAccessID: acc,
SignBytes: func(b []byte) ([]byte, error) {
_, signedBytes, signingError := appengine.SignBytes(ctx, b)
return signedBytes, signingError
},
Method: "PUT",
ContentType: contentType,
Expires: time.Now().Add(1 * time.Hour),
})
JS XHR
使用 Go 中的 SignedURL,即 xhr.open("PUT",signedUrl);
额外注释
SignedURL 由 Go API 生成,始终以 https://storage.googleapis.com/example-bucket/fileName
... 开头,我在其他地方读到它应该是 www.googleapis.com/storage
但我不认为这是问题所在,从官方 API 返回的 url 肯定是正确的。
我可以看到请求 header 包括:
访问控制请求 header :内容类型、x-upload-content-type
访问控制请求方法:PUT
来源:http://localhost:4000
所以看起来它勾选了所需 header 的所有框......
最佳答案
在 JS 方面,我通过 X-Upload-Content-Type
header 为文件上传设置附加元数据。
由于此 header 不在 CORS 配置中,因此请求失败。
通过将该 header 添加到配置中(例如提供给 gsutil cors set
配置文件的 responseHeader
列表),一切都按照问题中所述完全正常工作:)
关于google-app-engine - 带有 SignedURL 的 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47990400/