cyu / rack-cors

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

how can i add multiple origins in rack-cors #178

Open deepaksisodiaa opened 5 years ago

deepaksisodiaa commented 5 years ago

Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins 'http://localhost:3000, http://localhost:4000' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end

jkeam commented 5 years ago

https://github.com/cyu/rack-cors/issues/131

camallen commented 4 years ago

As specified in #131 you'll have to add multiple allow block entries to configure different origins, e.g.

allowed_headers = %i(get post put patch delete options head)
allow do
  origins 'http://localhost:3000'
  resource '*', headers: :any, methods: allowed_headers
end

allow do
  origins 'http://localhost:4000'
  resource '*', headers: :any, methods: allowed_headers
end
dchersey commented 4 years ago

This would be a good addition to the README!

rally25rs commented 4 years ago

The original post is passing a single string with a comma separated list to origins

origins 'http://localhost:3000, http://localhost:4000'

that is incorrect. origins takes multiple arguments. You should be passing multiple args as shown in the README:

https://github.com/cyu/rack-cors#rack-configuration

use Rack::Cors do
  allow do
    origins 'localhost:3000', '127.0.0.1:3000',
            /\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/
            # regular expressions can be used here

The code loops through the origins and checks each for a match https://github.com/cyu/rack-cors/blob/dbea904a7767aef89f48686635add60157144d42/lib/rack/cors/resources.rb#L42-L50

So you should be passing

origins 'http://localhost:3000', 'http://localhost:4000'

(passing 2 strings as opposed to passing 1 comma separated string)

cickes commented 3 years ago

How can we pass an environment variable to origins?

The environment variable must be a string so separate the domains by a whitespace. Environment variable:
CORS_ORIGINS = 'domain1.com domain2.com anotherone.com'

origins ENV.fetch('CORS_ORIGINS').split(" ").map { |e| "'#{e.strip}'" }.join(", ").tr('"', "")

Yields: "'domain1.com', 'domain2.com', 'anotherone.com'"

This won't work because it is a string instead of a comma separated list. One way to get this to work is to loop through the values similar to Cam's answer

cyu commented 3 years ago

@cickes try this:

origin *ENV.fetch('CORS_ORIGINS').split(" ").map(&:strip)

sandstrom commented 2 years ago

I'm doing some issue gardening 🌱🌿 🌷 and came upon this issue. Since it's quite old I just wanted to ask if this is still relevant? If it isn't, maybe we can close this issue?

By closing some old issues we reduce the list of open issues to a more manageable set.