使用ListBucketsCommand调用Backblaze B2 S3兼容API时的CORS问题
Backblaze B2 S3兼容API调用CORS问题解决方案
问题背景
开发S3导航器时,在Angular应用中使用AWS SDK的S3Client调用Backblaze B2的S3兼容API,鉴权并列出存储桶的代码在Wasabi、IDrive E2等服务商环境中正常运行,但在Backblaze B2中出现CORS错误,即使配置了“与所有源共享此存储桶的所有内容”的CORS规则仍无法解决。
相关代码
import { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3'; async authenticateAccount( endpoint: string, accessKeyId: string, secretAccessKey: string ) { console.log('s3 client used'); if (!/^https?:\/\//i.test(endpoint)) { endpoint = `https://${endpoint}`; } try { new URL(endpoint); } catch (error) { console.error('Invalid endpoint URL:', endpoint); throw new Error('Invalid endpoint URL'); } console.log("entered url is", endpoint); const s3 = new S3Client({ region: 'us-east-005', //buckets are in this region in backblazeB2 endpoint, credentials: { accessKeyId, secretAccessKey, }, forcePathStyle: true, }); try { const command = new ListBucketsCommand({}); const response = await s3.send(command); return response; } catch (error) { console.error('Error getting bucket information:', error); throw error; } }
报错信息
Access to fetch at 'https://s3.us-east-005.backblazeb2.com/?x-id=ListBuckets' from origin 'http://localhost:4200' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
核心问题分析
你遇到的CORS错误根源在于:Backblaze B2的S3兼容API中,ListBuckets属于账户级操作,而你配置的CORS规则是针对存储桶级的——存储桶CORS仅对桶内的对象操作(如ListObjects、GetObject等)生效,账户级接口的响应不会携带Access-Control-Allow-Origin这类CORS头,因此浏览器会阻止跨域请求。
解决方案
1. 通过后端代理转发请求(推荐)
直接在Angular前端调用账户级S3接口会受限于浏览器CORS规则,最可靠的解决方式是搭建后端服务作为代理:
- 后端服务(如Node.js、Spring Boot等)使用AWS SDK调用Backblaze B2的
ListBuckets接口 - Angular前端向后端接口发起请求,后端将结果返回给前端
这种方式完全规避了浏览器跨域限制,同时也能避免在前端暴露敏感的访问密钥(前端直接存储密钥存在安全风险)。
2. 验证关键配置细节
虽然你已检查过基础信息,但可以再确认以下几点:
- 确认
region参数正确:us-east-005是Backblaze B2的有效区域,无需修改 - 检查访问密钥权限:确保密钥拥有
listBuckets权限(你提到在S3浏览器中可用,此步骤可快速跳过) - 无需调整
forcePathStyle:Backblaze B2兼容路径样式和虚拟主机样式,该设置不影响账户级操作
补充说明
其他S3兼容服务商(如Wasabi、IDrive E2)可能对账户级接口默认开启了CORS支持,因此你的代码在这些平台能正常运行,但Backblaze B2的设计逻辑不同,账户级接口不支持直接跨域调用。
内容的提问来源于stack exchange,提问作者Ahmad Irshad
相关产品推荐
相关产品推荐

