出现此问题通常是因为AWS S3没有设置跨域资源共享(CORS)配置。解决此问题的解决方案是为S3存储桶添加COR配置。
下面是使用AWS SDK for S3的Node.js的添加CORS配置的示例代码:
const AWS = require('@aws-sdk/client-s3');
const s3Client = new AWS.S3({ region: 'us-east-1' });
const params = {
Bucket: 'my-bucket',
CORSConfiguration: {
CORSRules: [
{
AllowedHeaders: ['Authorization'],
AllowedMethods: ['GET', 'PUT'],
AllowedOrigins: ['*'],
ExposeHeaders: ['Content-Length'],
MaxAgeSeconds: 3000,
},
],
},
};
s3Client.putBucketCors(params, (err, data) => {
if (err) {
console.log('Error: ', err);
throw err;
} else {
console.log('Success: ', data);
}
});
此示例将CORS配置添加到名为“my-bucket”的存储桶中。CORS规则允许GET和PUT方法,允许来自任何源头(*)的请求,并允许Authorization请求头。此外,Content-Length响应头暴露给客户端,并且此CORS规则将在3000秒内缓存。
完成此操作后,您应该能够在使用AWS SDK for S3时避免“No 'Access-Control-Allow-Origin' header is present on the requested resource”错误。