Skip to content

Instantly share code, notes, and snippets.

@truetechcode
Last active December 18, 2020 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save truetechcode/818955ca28ab3d3407cc70232bd9014a to your computer and use it in GitHub Desktop.
Save truetechcode/818955ca28ab3d3407cc70232bd9014a to your computer and use it in GitHub Desktop.
title published description tags cover_image
Setting Up CORS On A Rails App
true
Setting up CORS on a Rails API to allow communications with a front end app.
Rails, CORS, API, React

Problem

I was trying to integrate a Rails API with a React front end when I encountered an error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://immense-savannah-47088.herokuapp.com/api/v1/books. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing.

Solution

In an effort to solve the problem I tried several suggested solutions including this one I saw in a Medium article that requires the use of the rack-cors ruby gem.

1. Add rack-cors Gem

In your gemfile you should add the following line or in some cases, it is commented out, you just need to uncomment it:

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

2. Bundle install

After adding the rack-cors gem you will need to run the following command, to install the gem:

$ bundle install

3. Add the configuration in the Application.rb

Add the following lines of code to your application.rb file:

module YourApp
  class Application < Rails::Application

    # ...

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
  end
end

This should work as long as you won’t be using Heroku or other services that use Rack-based servers but if you intend to use Heroku then you will do this instead of the number three-step above.

4. Add the configuration in the Config.ru

Add the following lines of code to the end of your config.ru file:

# ....
 
require 'rack/cors'
use Rack::Cors do
 
 # allow all origins in development
 allow do
   origins '*'
   resource '*',
       :headers => :any,
       :methods => [:get, :post, :delete, :put, :options]
 end
end

Check the Ruby documentation for more information on using Rack middleware and the MDN to learn more about CORS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment