我正在尝试使用 JavaScript 从设置为
allPrivate
的 Backblaze 存储桶中获取图像。
我有一个正确的授权代码,如果我像这样获取图像,它就可以工作:
echo '<img src="' . $_SESSION["downloadUrl"] . '/file/' . $bucketName . '/' . $file[0] . '?Authorization=' . $_SESSION["authorizationToken"] . '" />';
但是,当我尝试使用 javascript 时,它失败了:
const myHeaders = new Headers();
myHeaders.append("Authorization", "<?php echo $_SESSION["authorizationToken"]; ?>");
const response = await fetch("<?php echo $_SESSION["downloadUrl"] . '/file/' . $bucketName . '/test/test.avif'?>" , {
method: 'GET',
headers: myHeaders
} );
if(response.ok) {
const blob = await response.blob(); // Convert to a blob for use as an image
const imageUrl = URL.createObjectURL(blob); // Create a local URL for the blob
// Display the image
b2.src = imageUrl;
} else {
console.error('Error fetching image:', response.statusText);
}
问题是 Backblaze 没有将
Access-Control-Allow-Origin
标头添加到选项/预检请求中。我已经使用命令行设置了 B2 CORS 规则。这就是我目前针对此存储桶的 CORS 规则:
"corsRules": [
{
"allowedHeaders": [
"authorization",
"x-bz-file-name",
"x-bz-content-sha1",
"x-bz-info-author"
],
"allowedOperations": [
"b2_upload_file"
],
"allowedOrigins": [
"https://example.com"
],
"corsRuleName": "uploadRules",
"exposeHeaders": [
"x-bz-content-sha1"
],
"maxAgeSeconds": 3600
},
{
"allowedHeaders": [
"range",
"referer",
"authorization",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
"user-agent"
],
"allowedOperations": [
"b2_download_file_by_id",
"b2_download_file_by_name"
],
"allowedOrigins": [
"https://example.com"
],
"corsRuleName": "downloadRules",
"exposeHeaders": [
"x-bz-content-sha1",
"access-control-allow-origin"
],
"maxAgeSeconds": 3600
}
]
我认为我已经正确设置了所有内容,但我一生都无法弄清楚如何让 B2 发送
access-control-allow-origin
标头。我缺少什么? B2 支持预检请求吗?
读完此页后,它说我一直在尝试做的事情是不可能的:
由于浏览器被明确要求从 CORS 请求中剥离用户标头,因此当这些请求来自浏览器时,无法在私有存储桶的下载请求中使用 AUTHORIZATION 标头。