问题描述
我正在尝试使用签名 URL 通过 Google 应用引擎使用 react 和 node 上传文件。 我能够生成签名 URL,但是在控制台中出现 CORS 错误时。当我在浏览器中打开签名 URL 时收到以下错误。
.bashrc
<Error>
<Code>MalformedSecurityHeader</Code>
<Message>Your request has a malformed header.</Message>
<ParameterName>content-type</ParameterName>
<Details>Header was included in signedheaders,but not in the request.</Details>
</Error>
这是我在 React 应用中的前端代码
async function generateV4UploadSignedUrl() {
const options = {
version: "v4",action: "write",expires: Date.Now() + 15 * 60 * 1000,// 15 minutes
contentType: "audio/wav",};
// Get a v4 signed URL for uploading file
const [url] = await gcTempFiles
.file(gcFileName)
.getSignedUrl(options);
console.log("Generated PUT signed URL:");
console.log(url);
console.log("You can use this URL with any user agent,for example:");
console.log(
"curl -X PUT -H 'Content-Type: application/octet-stream' " +
`--upload-file my-file '${url}'`
);
res.status(200).json({
success: true,msg: `url created`,data: { url},});
}
此外,我已经使用以下命令在存储桶级别设置了所有 CORS 策略
let file = files.map((f) => f.file);
console.log(file)
let xhr = new XMLHttpRequest();
xhr.open('PUT',signedurl,true);
xhr.setRequestHeader("Content-type","application/octet-stream");
xhr.onload = function (response) {
console.log('on-load',response);
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Status OK")
} else {
console.log("Status not 200")
}
}
};
xhr.onerror = function (response) {
console.log("Response error",response)
};
xhr.upload.onprogress = function (evt) {
// For uploads
if (evt.lengthComputable) {
var percentComplete = parseInt((evt.loaded / evt.total) * 100);
console.log("progress",percentComplete)
}
}
xhr.send(file);
cors.json 文件
gsutil cors set cors.json gs://bucket name
我再次在谷歌应用引擎上构建网络应用程序。并且需要签名 URL 来解决 32MB 限制。有人可以指出我做错了什么吗?因此,非常感谢任何有用的建议。
解决方法
我已使用以下代码在存储桶上配置 CORS 解决了该错误。它运行良好。
refresh$ = interval(5 * 1000).pipe(tap(() => this.load()));
fakehttp() {
return timer(10 * 1000).pipe(take(1));
}
load() {
this.fakehttp().subscribe((r) => {
console.log("data");
});
}
ngOnInit() {
this.refresh$.subscribe((r) => {
console.log("refresh!");
});
}