cyu / rack-cors

Rack Middleware for handling Cross-Origin Resource Sharing (CORS), which makes cross-origin AJAX possible.
MIT License
3.26k stars 263 forks source link

Expose a subdomain resource only to all origins #210

Closed xiaopow closed 3 years ago

xiaopow commented 3 years ago

I've got a subdomain constraint in routes.rb for my API endpoints, I want to expose this subdomain route for CORS. How can I do this?

# routes.rb
constraints subdomain: 'api' do
  namespace :api, path: '/' do
    namespace :v1 do
      # Flows
      post '/foo' => 'foo#create'

    end
  end
end

Will the following work for this case?

#application.rb
allow do
  origins '*'
  resource '/*',
    :headers => :any,
    :methods => [:get, :post, :patch, :options],
    :if => proc { |env| env['HTTP_HOST'] == 'api.foo.com' }
end

Or I can do something like this?

allow do
  origins '*'
  resource 'api.*', headers: :any, methods: [:get, :post, :patch, :put]
end
cyu commented 3 years ago

@xiaopow Using the :if option on a resource declaration should work

xiaopow commented 3 years ago

@cyu , so this solution?

# application.rb
allow do
  origins '*'
  resource '/*',
    :headers => :any,
    :methods => [:get, :post, :patch, :options],
    :if => proc { |env| env['HTTP_HOST'] == 'api.foo.com' }
end

My server serves both the api.foo.com and app.foo.com domains.

cyu commented 3 years ago

@xiaopow yes