Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amazon s3 Javascript- No 'Access-Control-Allow-Origin' header is present on the requested resource

Am trying to upload my file via:

console.log("not broken til here");
    scope.inputMemeIsFile=true;
    var bucket = new AWS.S3({params: {Bucket: 'townhall.images'}});
    file = image.file;
    console.log(file);

    var params = {Key: file.name, ContentType: file.type, Body: file};
      bucket.upload(params, function (err, data) {
        var result = err ? 'ERROR!' : 'UPLOADED.';
        console.log(result);
        console.log(err);
      });

However, am getting the following error:

XMLHttpRequest cannot load https://s3.amazonaws.com/<BUCKETNAME>/favicon.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:5000' is therefore not allowed access.

with the proceedingError: Network Failure {message: "Network Failure", code: "NetworkingError", time: Tue Feb 17 2015 13:37:06 GMT-0500 (EST), region: "us-east-1", hostname: "s3.amazonaws.com"…}

My CORS config looks like the following and I have tried a couple things with no luck.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://*</AllowedOrigin>
        <AllowedOrigin>https://*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Anyone have any idea whats wrong? I've looked at 5-6 similar posts but no one seems to be able to solve the problem.

like image 974
John Avatar asked Feb 17 '15 18:02

John


People also ask

How do I fix CORS policy no Access-Control allow origin?

< access-control-allow-origin: * You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it! Thanks this helps to avoid all the hassle and test the code from localhost.

How do I enable CORS on AWS?

Enable CORS support on a REST API resourceSign in to the API Gateway console at https://console.aws.amazon.com/apigateway . Choose the API from the APIs list. Choose a resource under Resources. This will enable CORS for all the methods on the resource.


4 Answers

In order to upload files via browser, you should ensure that you have configured CORS for your Amazon S3 bucket and exposed the "ETag" header via the ETag declaration.

I would suggest you start with an open test configuration and then modifying it to your needs:

<?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>     <ExposeHeader>ETag</ExposeHeader>   </CORSRule> </CORSConfiguration> 

Then check your bucket permissions and your AWS configuration (accessKeyId, secretAccessKey, and region) since none of these are present in your snippet.

For testing, go to your IAM Management Console and create a new IAM user named prefix-townhall-test then create a group with this simple policy that grants access to a bucket:

{   "Version": "2012-10-17",   "Statement": [     {       "Effect": "Allow",       "Action": ["s3:ListBucket"],       "Resource": ["arn:aws:s3:::test-bucket-name"]     },     {       "Effect": "Allow",       "Action": [         "s3:PutObject",         "s3:GetObject",         "s3:DeleteObject"       ],       "Resource": ["arn:aws:s3:::test-bucket-name/*"]     }   ] } 

Make sure the user you created is using the new group with this policy.

Now create a simple test script like the one used on amazon this:

HTML

<input id="file-chooser" type="file" /> <button id="upload-button">Upload</button> <p id="results"></p> 

CODE (on DOM ready)

// update credentials var credentials = {accessKeyId: 'new accessKeyId', secretAccessKey: 'new secretAccessKey'}; AWS.config.update(credentials); AWS.config.region = 'us-west-1';  // create bucket instance var bucket = new AWS.S3({params: {Bucket: 'test-bucket-name'}});  var fileChooser = document.getElementById('file-chooser'); var button = document.getElementById('upload-button'); var results = document.getElementById('results'); button.addEventListener('click', function() {     var file = fileChooser.files[0];     if (file) {         results.innerHTML = '';          var params = {Key: file.name, ContentType: file.type, Body: file};         bucket.upload(params, function (err, data) {             results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';         });     } else {         results.innerHTML = 'Nothing to upload.';     } }, false); 
like image 196
jungy Avatar answered Oct 07 '22 01:10

jungy


Some browsers, such as Chrome, do not support localhost or 127.0.0.1 for CORS requests.

Try using instead: http://lvh.me:5000/

See https://stackoverflow.com/a/10892392/1464716 for more.

like image 37
Edu Lomeli Avatar answered Oct 07 '22 00:10

Edu Lomeli


The current answer is pretty outdated. So here's my sharing:

First you need to setup CORS on your AWS S3 bucket

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST",
            "DELETE",
            "HEAD"
        ],
        "AllowedOrigins": [
            "http://*",
            "https://*"
        ],
        "ExposeHeaders": [
            "Access-Control-Allow-Origin",
            "ETag"
        ],
        "MaxAgeSeconds": 3000
    }
]

Just a note on the cors for S3. When applying a policy, files already in the bucket are NOT updated. So make sure you apply a CORS policy to only new buckets, or re-add the content after applying the policy. Old content won't be affected by new CORS policy

How amazon S3 evaluate CORS?

  • The request's Origin header must match an AllowedOrigin element.
  • The request method (for example, GET or PUT) or the Access-Control-Request-Method header in case of a preflight OPTIONS request must be one of the AllowedMethod elements.
  • Every header listed in the request's Access-Control-Request-Headers header on the preflight request must match an AllowedHeader element.

For the last step, You need to clear cache on browser also because browser might cache the previous pre-flight request

like image 21
X Sham Avatar answered Oct 07 '22 01:10

X Sham


Try <AllowedOrigin>*</AllowedOrigin>, without protocol.

If it has no effect – you probably have problem on client side.

like image 32
ermouth Avatar answered Oct 07 '22 00:10

ermouth