add cors headers to a http server with a specific origin in ruby

To add CORS headers to a Ruby HTTP server (such as one built with Rack), you can use the rack-cors gem. Here's an example of how to add rack-cors to your application:

  1. Add the rack-cors gem to your Gemfile and run bundle install:

    main.rb
    gem 'rack-cors'
    
    16 chars
    2 lines
  2. Configure rack-cors in your application. Here's an example configuration that allows requests from http://example.com:

    main.rb
    # In config.ru
    require 'rack/cors'
    
    use Rack::Cors do
      allow do
        origins 'http://example.com'
        resource '*', headers: :any, methods: [:get, :post, :put, :delete, :options]
      end
    end
    
    189 chars
    10 lines

    This configuration allows requests from http://example.com to any endpoint (*) using any HTTP method.

    You can further customize the allow block to specify more specific URL and HTTP method restrictions.

  3. Start your application and test requests from the allowed origin.

related categories

gistlibby LogSnag