简体   繁体   English

CORS 在 React-Vite 应用程序中上传到 S3

[英]CORS while uploading to S3 in React-Vite application

I am trying to upload a file to s3 using aws sdk on a react application.我正在尝试在 React 应用程序上使用 aws sdk 将文件上传到 s3。 However I bumped into CORS error and even after configuring the CORS policy for my bucket the error still persist.但是,我遇到了 CORS 错误,即使在为我的存储桶配置了 CORS 策略之后,错误仍然存在。

My CORS policy for the bucket is as follow:我的 CORS 存储桶策略如下:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "http://localhost:3000"
        ],
        "ExposeHeaders": []
    }
]

And this is my code to upload my blob:这是我上传 blob 的代码:

import * as AWS from 'aws-sdk';

const s3 = new AWS.S3({
    accessKeyId: "access key id",
    secretAccessKey: "secret access key",
});

export const uploadToS3 = (fileContent: Blob, fileName: string, bucket: string) => {
    console.log('attempting to upload to s3')
    const params = {
        Bucket: bucket,
        Key: fileName,
        Body: fileContent
    }

    s3.upload(params, function (err: any, data: any) {
        if (err) {
            console.log(err);
        } if (data) {
            console.log(data);
        }
    });
}

And this is the console output.这是控制台 output。

Access to XMLHttpRequest at 'https://.s3.amazonaws.com/testing.png' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略已阻止从源“http://localhost:3000”访问“https://.s3.amazonaws.com/testing.png”上的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”header。

I wasn't exactly sure what happened, but I deleted the bucket and created an identical one (as far as I am concerned) and I am getting a different error message, saying我不确定发生了什么,但我删除了存储桶并创建了一个相同的存储桶(就我而言),我收到了一条不同的错误消息,说

The authorization header is malformed; the region 'us-east-1' is wrong; expecting 'ap-southeast-2'

Hence I have to include region in my s3 instantiation.因此,我必须在我的 s3 实例化中包含区域。

const s3 = new AWS.S3({
    accessKeyId: "access key id",
    secretAccessKey: "secret access key",
    region: "bucket region" // <-------------- was missing
});

Now I can put object on my bucket as intended, I will try to recreate the error and see what was the difference between my first and second bucket.现在我可以按预期将 object 放入我的存储桶中,我将尝试重新创建错误并查看我的第一个和第二个存储桶之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM