add cors headers to a http server in ruby

To add CORS headers to a Ruby HTTP server, you can use the Rack middleware Rack::Cors. Here's an example of how to use it:

main.rb
require 'rack/cors'
require 'webrick'

app = lambda do |env|
  # your application logic here
end

options = {
  :allow_origins => '*',  # replace * with the domains you want to allow
  :allow_methods => [:get, :post, :put, :patch, :delete, :options],
  :allow_headers => :any,
  :expose_headers => ['X-My-Custom-Header'],
  :max_age => 600
}

handler = Rack::Handler::WEBrick
server = handler.run Rack::Cors.new(app, options), :Port => 9292
441 chars
18 lines

In the options hash, you can specify which origins, methods, and headers you want to allow. The expose_headers option can be used to list custom headers that should be exposed to the client. Finally, the max_age option specifies how long the browser is allowed to cache the CORS response.

With this middleware in place, any HTTP responses from your application will automatically include the appropriate CORS headers.

gistlibby LogSnag