CORS is not working as per gem 'rack-cors' in ruby '2.7.6', rails '5.1.7'

47 views Asked by At
require 'rack/cors'

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins CORS_ORIGINS[Rails.env]
    resource '*', :headers => :any, :methods => [:get, :post, :options, :put, :delete],credentials: true
  end
end

I'm using gem 'rack-cors' This was worked fine for my different project but currently in ruby '2.7.6', rails '5.1.7' I'm facing some issue, I'm not sure is this because of the version of ruby on rails or else.

/config/initializers/cors.rb

as mentioned in gem 'rack-cors', code written in above file, also tried in config.ru, later tried in /config/application.rb

I'm printing some message like,

Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        puts "************cors************"
        origins CORS_ORIGINS[Rails.env]
        resource '*', :headers => :any, :methods => [:get, :post, :options, :put, :delete],credentials: true
      end
    end

This message is also printing in above cases but when deploying on server, this is not working.

1

There are 1 answers

0
Archer On

I have an almost similar environment and have a working CORS Management. Maybe this helps. I Sort out origins fesert, then putting Resource.

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins do |source, _env|
      # this proc should return true or false
      # You can dynamically check the database/redis or any other storage for your origins
      Origin.list.include?(Addressable::URI.parse(source)&.host)
    end
    resource '*',
             headers: %i[get post options put delete],
             methods: :any
  end
end