5

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
aks
  • 6,072
  • 4
  • 43
  • 68

1 Answers1

8

To allow cross-origin requests for only a particular 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.

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153