我正在尝试使用签名 URL 使用 React 和 Node.js 通过 Google 应用程序引擎上传文件。
我能够生成签名 URL,但在控制台中收到 CORS 错误时。当我在浏览器中打开签名 URL 时,收到以下错误。
<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>
这是我的 Node js 代码,用于生成签名 Url
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},
});
}
这是我在反应应用程序中的前端代码
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 策略gsutil cors set cors.json gs://bucket name
cors.json 文件
[{"origin": ["*"],
"responseHeader": ["X-Requested-With", "Access-Control-Allow-Origin", "Content-Type"],
"method": ["GET", "HEAD", "POST"],
"maxAgeSeconds": 3600}]
我再次在谷歌应用程序引擎上构建网络应用程序。并且需要对 URL 进行签名才能解决 32MB 限制。有人可以指出我做错了什么吗?因此,任何有用的建议都将受到高度赞赏。