要解决Amazon S3中的Access-Control-Allow-Origin问题,您可以使用以下代码示例:
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var params = {
Bucket: 'your-bucket-name',
Key: 'your-object-key',
ACL: 'public-read',
ContentType: 'your-content-type',
Body: 'your-object-body',
Metadata: {
'Custom-Header': 'your-custom-header-value'
},
CORSConfiguration: {
CORSRules: [
{
AllowedOrigins: ['*'],
AllowedMethods: ['GET', 'PUT', 'POST', 'DELETE'],
AllowedHeaders: ['*'],
MaxAgeSeconds: 3000
}
]
}
};
s3.putObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
});
aws s3api put-object \
--bucket your-bucket-name \
--key your-object-key \
--acl public-read \
--body your-object-body \
--content-type your-content-type \
--metadata '{"Custom-Header":"your-custom-header-value"}' \
--cors-configuration '{"CORSRules":[{"AllowedOrigins":["*"],"AllowedMethods":["GET","PUT","POST","DELETE"],"AllowedHeaders":["*"],"MaxAgeSeconds":3000}]}'
上述示例代码会在上传对象到Amazon S3时设置Access-Control-Allow-Origin为允许所有来源(),允许的方法为GET、PUT、POST和DELETE,允许的头部为所有(),并设置最大缓存时间为3000秒。
请将示例代码中的your-bucket-name替换为您的存储桶名称,your-object-key替换为您的对象键,your-content-type替换为您的对象内容类型,your-object-body替换为您要上传的对象内容,your-custom-header-value替换为您自定义的头部值。