Rails apiSort Order

Rails API: Setting up Cors - [003]

Setting up CORS is going to be important when building APIs it allows us to configure how clients can access our server. We'll start off by installing the rack-cors gem. We'll be able to understand more as we progress.

Installing Rack Cors

In our Gemfile simply add the following line.

gem 'rack-cors', require: 'rack/cors'

Configuring Rack Cors

In config/application.rb we're going to add the following code.

config.middleware.insert_before 0, Rack::Cors do  allow do    origins '*'    resource(      '*',      headers: :any,      methods: [:get, :patch, :put, :delete, :post, :options]    )  endend

What this setting does is it tells our rails app to be able to accept requests from any origin the * represents 'all' origins. We're also specifying what headers the client can pass to our api and what http methods we will accept. Our client should now be able to make AJAX requests to the API endpoint.