gpt4 book ai didi

javascript - AWS - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin' header is present on the requested resource

转载 作者:行者123 更新时间:2023-12-01 03:32:42 25 4
gpt4 key购买 nike

我对 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.

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

这是我的凭据代码:

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}
});

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

最佳答案

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>

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);
});
});

关于javascript - AWS - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com