4

I've downloaded the rack-cors gem, followed the documentations and tried to configure the CORS settings inside my Amazon AWS s3 bucket to accept GET requests from my site but I still keep getting the same error in my console.

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>https://[url]</AllowedOrigin>
        <AllowedOrigin>http://[url]</AllowedOrigin>
        <AllowedOrigin>http://localhost:3000</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

XMLHttpRequest cannot load [audio_url_from_amazon]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin [my_website_url] is therefore not allowed access.

Any help with this would be awesome as I've read other questions but still can't seem to get the right config working.

Chris
  • 391
  • 4
  • 14
  • When you write to the bucket what permissions are you setting? I use the s3 gem and I had a similar issue that was solved by setting record.acl = :public_read but that is a dsl from the gem so I am not sure the syntax on how to hand roll it. – ruby_newbie Jul 13 '16 at 07:09
  • In which file did you insert that code once you had the gem installed @ruby_newbie – Chris Jul 13 '16 at 08:08
  • [I don't think CORS works with the magic hostname `localhost`.](http://stackoverflow.com/a/10892392/1695906) Is that what you're testing against? – Michael - sqlbot Jul 13 '16 at 10:49
  • I added it when I am writing to s3. `def write(path, content) bucket = get_bucket record = bucket.objects.build(path) record.content = content record.acl = :public_read record.save end` – ruby_newbie Jul 13 '16 at 15:27
  • I am testing both localhost and live site, it wouldn't really matter if I could get it to work on the live site and not localhost @sqlbot. – Chris Jul 13 '16 at 17:42

2 Answers2

0

Add gem 'rack-cors' to your gemfile, run bundle. Create a new initializer cors.rb. Add the following code there

Rails.application.config.middleware.insert_before 0, 'Rack::Cors' do
   allow do
    origins '*'

  resource '*',
    headers: :any,
    methods: [:get]
  end
end

This should fix your issue.

Vasanth
  • 108
  • 7
0

Very late to the question, but had the same issue, while it looks as the the browser is firing an OPTIONS request for preflight, s3 CORS will not allow OPTION as it's an HTTP concept.

Solution for me was to allow PUT requests in s3 CORS config...

<AllowedMethod>PUT</AllowedMethod>

which allows the preflight to succeed.

IT_puppet_master
  • 702
  • 5
  • 20