6

I know there seem to be some answers related to this topic, but none of them worked for me so far. I built a rails API backend with a front end built with React. The application was running fine but after I added some features and deployed again I started having issues with my CORS. The feature I added was related to Redis and Action cable. Now I am getting this error: Access to XMLHttpRequest at 'https://myestateapi.herokuapp.com/top_apartment' from origin 'https://frozen-bastion-98066.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. my setting have not changed I don't know why I am getting this. In my config/application.rb I have this

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

        resource '*',
                 headers: :any,
                 methods: %i[get post put patch delete options head]
      end
    end

This very code worked fine. What could be causing this error? Or can anyone suggest a better gem than rack-cors? I would be grateful to have help from anyone. Thank you in advance.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Addo
  • 273
  • 3
  • 8

3 Answers3

10

If you are using Rails 6:

First go to your Gemfile and uncomment gem 'rack-cors'. Then run bundle install

After that go to config/initializers folder. There, you should find a file called cors.rb.

Uncomment the code that looks like this

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

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

change the line that says origins 'example.com' to origin '*' or if you're request will be originating from a particular origin, then set it accordingly.

This worked for me. Hope it works for you as well. Cheers

Phillip Musiime
  • 167
  • 2
  • 12
1

I have figured it out. There were issues with my serializer, so I removed it completely and it worked. For people using rails, please run the command heroku run rails s to see if there is any impediment it would be logged in the console for you to address it.

Addo
  • 273
  • 3
  • 8
0

I think you can get the answer in this topic:

Heroku, Rails 4, and Rack::Cors

Hope it help. thanks

Quân Hoàng
  • 371
  • 3
  • 9