aks
aks

Reputation: 9491

How to enable CORS for only selected route rails

I am on Rails5 and I want to allow CORS on one of my route. Here is how I can allow CORS for all my route, but is there a way to only whitelist for one endpoint?

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

Upvotes: 6

Views: 4504

Answers (1)

sideshowbarker
sideshowbarker

Reputation: 88096

To allow cross-origin requests for only a certain endpoint path, use it as the first resource arg:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '/endpoint/to/allow', :headers => :any, :methods => [:get, :post, :options]
  end
end

That’ll allow cross-origin requests only for the path /endpoint/to/allow.

If you want to allow multiple paths, you can specify multiple resource declarations:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '/endpoint/to/allow', :headers => :any, :methods => [:get, :post, :options]
    resource '/another/endpoint/', :headers => :any, :methods => [:get, :post, :options]
  end
end

https://github.com/cyu/rack-cors#resource has more details.

Upvotes: 11

Related Questions