使用AWS SDK for S3复制对象时遇TypeError: headers[headerName].trim错误
AWS S3 CopyObjectCommand 报错:TypeError: headers[headerName].trim is not a function
问题代码
import { CopyObjectCommand, S3Client } from '@aws-sdk/client-s3'; const s3Client = new S3Client({}); ... const params = { Bucket: "destination_bucket", // 目标存储桶名 Key: "abc.pdf", // 目标文件名 CopySource: { Bucket: "source_bucket", // 源存储桶名 Key: "xyz.pdf" // 源文件名 } }; const command = new CopyObjectCommand(params); const response = await s3Client.send(command);
报错信息
TypeError: headers[headerName].trim is not a function at getCanonicalHeaders (/var/task/index.js:38660:62) at SignatureV4S3Express.signRequest (/var/task/index.js:38978:80) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
解决方法
这个错误的核心原因是CopySource参数格式不符合AWS SDK v3要求:SDK v3中CopySource必须传入字符串,而非你当前使用的对象格式。
修正后的参数写法如下:
const params = { Bucket: "destination_bucket", // 目标存储桶名 Key: "abc.pdf", // 目标文件名 // 格式:源存储桶名/源文件键 CopySource: "source_bucket/xyz.pdf" };
如果源文件键包含特殊字符(比如空格、中文、特殊符号),需要对桶名和文件键分别做URL编码:
const sourceBucket = "source_bucket"; const sourceKey = "xyz 中文.pdf"; const encodedCopySource = `${encodeURIComponent(sourceBucket)}/${encodeURIComponent(sourceKey)}`; const params = { Bucket: "destination_bucket", Key: "abc.pdf", CopySource: encodedCopySource };
补充说明
你之前用对象传递CopySource是AWS SDK v2的写法,但v3的CopyObjectCommand已不再支持该格式。SDK内部解析错误格式的参数时,会导致请求头处理环节出现类型错误,这和你是否拥有权限无关——哪怕权限完全合规,参数格式错误也会触发这个报错。
内容的提问来源于stack exchange,提问作者H. Pardess
相关产品推荐
相关产品推荐

