Home > Enterprise >  Implementing a Regex solution in Rack CORS
Implementing a Regex solution in Rack CORS

Time:06-08

In order to bypass CORS issues, I have inserted a regular expression to catch all incoming urls (the first 6 digits can vary). However this is only functioning when the regexp is taken out, despite the Rack::Cors documentation indicating this is possible. What steps can I take to resolve this issue? What am I not thinking here that could be a potential issue?

Working:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins %w[100200.apps.zdusercontent.com 222334.apps.zdusercontent.com ]
    resource '*', headers: :any, methods: %i[get post head]
  end

Not Working:

config.middleware.insert_before 0, Rack::Cors do
 allow do
   origins %w[/\Ahttps:\/\/[0-9]{1,6}\.apps\.zdusercontent\.com\z/]
   resource '*', headers: :any, methods: %i[get post head]
 end

Error:

Failed to load https://100200.app.zdusercontent.com: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CodePudding user response:

Why are you passing array to origins when you are using regex? Can you try like this?

config.middleware.insert_before 0, Rack::Cors do
 allow do
   origins /\Ahttps:\/\/[0-9]{1,6}\.apps\.zdusercontent\.com\z/
   resource '*', headers: :any, methods: %i[get post head]
 end 
end

If you are using Rails 6 and above, check if you need to add hosts in application.rb file too.

  • Related