我正在尝试在我的 WIX 网站上创建一个简单的页面/表单,以允许我的用户上传文件。我必须为我的客户提供一个他们可以安全上传文件的工具,而且我认为它足够简单,可以用我的基本编码技能进行管理。原来不是!
我在控制台中收到以下错误:
Access to XMLHttpRequest at 'https://storage.googleapis.com/upload-test-01/sample.pdf' from origin 'https://www.mywebsite.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是我所做的:
我在名为 SecureUpload 的项目中创建了一个 upload-test-01 存储桶。
我还在这个项目上创建了一个服务帐户并将其命名为SecureUpload-SA并分配了
然后我在存储桶上设置以下 cors.json 文件:
[
{
"origin": ["https://www.mywebsite.com"],
"method": ["PUT"],
"responseHeader": ["*"],
"maxAgeSeconds": 3600
}
]
这是我在表格中使用的代码:
$w.onReady(function () {
console.log(`Ready is called`);
$w("#wixForms1").onWixFormSubmit(function () {
console.log(`WixFormSubmit is called`);
const file = $w("#uploadButton1").value[0];
const fileName = file.name;
const bucketName = "upload-test-01";
const apiKey = "myapikey";
const xhr = new XMLHttpRequest();
xhr.open("PUT", `https://storage.googleapis.com/${bucketName}/${fileName}`);
xhr.setRequestHeader("Authorization", `Bearer ${apiKey}`);
xhr.setRequestHeader("Access-Control-Allow-Origin", '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.onerror = function () {
console.log(`Error occurred while uploading the file: ${xhr.status}`);
};
xhr.onload = function () {
if (xhr.status === 200) {
console.log("File uploaded successfully.");
} else {
console.log(`Failed to upload file. Status code: ${xhr.status}`);
}
};
xhr.send(file);
});
});
bucket上的CORS设置是正确的,但是还是出现上面的错误。 如果有任何建议,我将不胜感激。