Lance Shi
Lance Shi

Reputation: 1187

Using AWS javascript sdk getting No Access-Control-Allow-Origin error

I am using AWS javascript browser version to upload a file into AWS S3 server. And I am getting the following error:

XMLHttpRequest cannot load https://s3-ap-southeast-2.amazonaws.com/cortex.myauscript.upload/uploadcontent-upload-development/TestFileName.txt. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

I have searched about this error but I can confirm that the CORS setting on that bucket is setted correctly. So I am a bit confused here.

Below is my code:

    var bucketName = 'cortex.myauscript.upload';
    AWS.config.region = 'ap-southeast-2';
    AWS.config.update({
        accessKeyId : 'test',
        secretAccessKey : 'test'
    });

    var bucket = new AWS.S3({
        params: {
            Bucket: bucketName
        }
    });

    var fileChooser = document.getElementById('file-chooser');
    var button = document.getElementById('upload-button');
    var results = document.getElementById('results');

    $("#upload-button").click(function() {
        var file = fileChooser.files[0];
        if(file) {
            var params = {
                Key: 'uploadcontent-upload-development/TestFileName.txt',
                ContentType: file.type,
                Body: file
            };
            bucket.upload(params).on('httpUploadProgress', function(evt){
                console.log("Uploaded :: " + parseInt((evt.loaded * 100) / evt.total)+'%');
            }).send(function(err, data) {
                alert("File uploaded successfully.");
            });
        }
    });

I am also a little bit wondering, will the wrong key/security key generate the same error. I am not 100% sure about that.

Thanks.

Upvotes: 0

Views: 345

Answers (1)

Khalid T.
Khalid T.

Reputation: 10547

It seems you're running your app from file:// instead of http:// which produces a null origin that cannot be authorized.

Upvotes: 1

Related Questions