Last Updated: February 25, 2016
·
2.283K
· georgiee

Wildcard CORS in RAILS

I searched for an easy solution for a wildcard CORS response in Rails.

I found two ways to do it.
There is that stupid rack-cors gem, which didn't work at all (middleware use, insert before, after..).
And you can build a combination of before_filter (for the headers), a real action in your controller (with no content) which gets called by a route.

I couldn't find a simple solution to drop in my routes. I remembered that routes.rb can execute RACK apps, I tried to search for "rack proc cors routes.rb". Nothing. So I had to do it myself.

Here we go:

if Rails.env.development?
    match "/your/url" => proc { |env| [
      200,
      {
        "Content-Type" => 'text/plain',
        "Access-Control-Allow-Origin" => '*',
        "Access-Control-Allow-Methods" => %w{GET POST PUT DELETE}.join(","),
        "Access-Control-Allow-Headers" => %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",")
      },
      ["Hello, world"]
    ]},  via: [:options]
  end

Just replace match "/your/url" with your existing route/url which should support the [OPTIONS] call for the CORS request. You can also use wildcard urls like '/your/*'.
The route is wrapped in Rails.env.development? so it never ever leaks in production :)

I had some static JS content under 0.0.0.0:4567 and needed to call my rails app under 0.0.0.0:3000. So easy to run into a CORS problem.

Enjoy.

1 Response
Add your response

It seems that this stopped working. I'm absolutely sure that this worked the the time of posting. Now it's required to send the cors headers additionally with every request not only in the OPTIONS preflight. I tried the cors gem again and no it works with their wildcard example. God I hate to debug CORS errors.

over 1 year ago ·