You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS SDK v3配置CORS时遇XAmzContentSHA256Mismatch错误求助

解决AWS SDK v3操作DigitalOcean Spaces时的XAmzContentSHA256Mismatch错误

错误详情

{
  '$metadata': {
    httpStatusCode: 400,
    requestId: 'tx000000000000006119f03-00644b4bf3-2e418004-sgp1b',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  Code: 'XAmzContentSHA256Mismatch'
}

问题代码

const client = new S3Client({
    region: 'us-east-1',
    endpoint: `https://sgp1.digitaloceanspaces.com`,
    credentials: {
      accessKeyId: key,
      secretAccessKey: key,
    },
  });
await s3Client().send(new PutBucketCorsCommand(params));

解决方案

1. 修正Region与签名配置

DigitalOcean Spaces的region需与实际机房一致(此处为sgp1),同时必须明确指定签名版本为v4:

const client = new S3Client({
  region: 'sgp1', // 替换为对应Spaces的region
  endpoint: `https://sgp1.digitaloceanspaces.com`,
  credentials: {
    accessKeyId: YOUR_ACCESS_KEY, // 填入正确的Access Key
    secretAccessKey: YOUR_SECRET_KEY, // 填入正确的Secret Key
  },
  signingRegion: 'sgp1',
  signatureVersion: 'v4',
});

2. 修复凭证变量错误

原代码中accessKeyId和secretAccessKey共用同一个key变量,这会直接导致签名计算错误,必须分别填入正确的Access Key和Secret Key。

3. 验证CORS配置格式

确保params中的CORS配置符合S3规范,示例正确格式:

const params = {
  Bucket: 'your-bucket-name',
  CORSConfiguration: {
    CORSRules: [
      {
        AllowedHeaders: ['*'],
        AllowedMethods: ['GET', 'POST'],
        AllowedOrigins: ['https://your-domain.com'],
        MaxAgeSeconds: 3000
      }
    ]
  }
};

4. 避免请求体编码问题

若仍报错,可显式设置请求的Content-Type,防止SDK自动编码引发SHA256不匹配:

const command = new PutBucketCorsCommand({
  ...params,
  Headers: {
    'Content-Type': 'application/xml'
  }
});
await client.send(command);

内容的提问来源于stack exchange,提问作者Jazuly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:42:26