ILoveET
ILoveET

Reputation: 139

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. However I bumped into CORS error and even after configuring the CORS policy for my bucket the error still persist.

My CORS policy for the bucket is as follow:

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

And this is my code to upload my 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.

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.

Upvotes: 1

Views: 738

Answers (1)

ILoveET
ILoveET

Reputation: 139

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.

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.

Upvotes: 0

Related Questions