skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. I think you can get the answer in this topic:

    Heroku, Rails 4, and Rack::Cors

    Hope it help. thanks

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search