AWS - 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头

cal*_*ers 8 javascript amazon-s3 amazon-web-services

我对 AWS 还很陌生,所以请耐心等待:(

我目前正在制作一个具有上传照片功能的网络应用程序。我想将这些照片保存在 S3 存储桶中,并将对它们的引用保存在我的数据库中。我目前正在遵循本指南:http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html

但是,我已经完成了指南中所述的所有操作(或者至少我希望如此),但是当我运行应用程序并运行该createAlbum()方法时,我收到错误:

XMLHttpRequest cannot load https://my-bucket-name.s3-us-west-2.amazonaws.com/myalbumname/. 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

我确保存储桶权限中允许所有用户拥有权限,我按照文档的指示更新了 CORS 配置,并更新了角色策略。

这是我的凭据代码:

var albumBucketName = 'my-bucket-name'; //not the real value, obviously
var bucketRegion = 'us-west-2';
var IdentityPoolId = 'my-identity-pool-id'; //here, too
AWS.config.update({
  region: bucketRegion,
  credentials: new AWS.CognitoIdentityCredentials({
  IdentityPoolId: IdentityPoolId
});
var s3 = new AWS.S3({
  apiVersion: '2006-03-01',
  params: {Bucket: albumBucketName}
});
Run Code Online (Sandbox Code Playgroud)

我一直在尝试寻找解决方案但没有成功。有谁知道我需要做什么来解决这个问题?任何帮助是极大的赞赏!谢谢。

小智 5

S3 存储桶上的 CORS:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)

AllowedOrigin 中的 * 可以用于测试目的。

您的存储桶将需要临时凭证,您可以做的是:

 // Set the region where your identity pool exists 
    AWS.config.region = 'us-east-1';

    // Configure the credentials provider to use an identity pool for temp 
    credentials
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'IDENTITY_POOL_ID',
    });

    // Make the call to obtain credentials
    AWS.config.credentials.get(function(){

    // Credentials will be available when this function is called.
    var accessKeyId = AWS.config.credentials.accessKeyId;
    var secretAccessKey = AWS.config.credentials.secretAccessKey;
    var sessionToken = AWS.config.credentials.sessionToken;

    var bucketName = 'bucket_name';

    var keyName = "key_name";

    var params = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};

    s3.putObject(params, function (err, data) {
    if (err)
    console.log(err)
    else
    console.log("Successfully uploaded data to " + bucketName + "/" + 
    keyName);
    });
    });
Run Code Online (Sandbox Code Playgroud)