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

To add CORS headers to a HTTP server with a specific origin and methods in Ruby, you can use the rack-cors middleware.

Here's an example of how to use it:

main.rb
require 'rack/cors'

# Define the allowed origins and methods
allowed_origins = ['https://example.com']
allowed_methods = %i[get post]

# Create the middleware with the options
use Rack::Cors do
  allow do
    origins allowed_origins
    methods allowed_methods
  end
end

run YourApp.new
289 chars
16 lines

In this example, we first require the rack/cors module. We then define the allowed origins and methods as arrays.

Next, we create the middleware using Rack::Cors, and specify the allow option. We use the origins method to set the allowed origins, and methods to set the allowed methods.

Finally, we run our app, which can be any Rack-compatible app.

With this middleware, requests with an origin not in allowed_origins or a method not in allowed_methods will be rejected with a CORS error.

gistlibby LogSnag