Setting up CORS for Rails API App

Aman Kumar
1 min readJun 2, 2020

--

Anyone who has worked with API has faced the CORS error anytime while attempting a request. For anyone unaware CORS refers to ‘Cross-Origin Resource Sharing’ and it is essentially how the server filters out requests from an origin other than itself.

While making an application usually on a single host, CORS may not be your concern as any request from the frontend will eventually be made to the same domain. But when building an API application, you need to either expect requests made from any origin or have a list of origins that are white-listed.

This blog deals with handling CORS issues by allowing requests from anywhere to be allowed at the server end in RAILS.

1. Add rack-cors Gem to Gemfile

gem 'rack-cors'

2. Run bundle Install

bundle install

3. Add rack-cors configuration in config/Application.rb

Add the script as per your Rails version.

Notice, when using Rails 5 or 6 remove the quotes around “Rails::Cors”

The above script lets all requests, given they are GET, POST or OPTION requests.

This will solve your problem with CORS.

References

Rack Cors

--

--