Tomoya's Blog

What is CORS?

May 11, 2020 • ☕️ 2 min read

Hi, I’m Tomoya. How’s it going guys?
This time I’ll be writing a memo about what CORS is and how to make use of it in Rails API mode.

What is CORS?

CORS stands for ”Cross Origin Resource Sharing”. In a nutshell, it allows your application to recieve requests from external origins which are specified by CORS configuration.

If you’re developing React as front-end and Rails (API) as back-end individually, you definitely need to configure CORS in RailsAPI in order to recieve requests from the React side of the project.

How to configure

On this post, I’ve already created sample React × Rails (API) project. So I’m using the sample app to show how to configure CORS for its project.

First, let’s install rack-cors to start off the CORS configuration.
Uncomment gem 'rack-cors' in Gemfile, and run bundle install.

Gemfile

# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors' # here

After installing rack-cors, you’ll notice you have cors.rb in config/initializers. Add the configuration below.

cors.rb

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'http://localhost:3000' # URL used for React-side
        resource '*',
        :headers => :any,
        :methods => [:get, :post, :patch, :delete, :options],
      end
    end

If you want to store session data with cookie, you also need to add credentials: true to the same file.

cors.rb

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'http://localhost:3000'
        resource '*',
        :headers => :any,
        :methods => [:get, :post, :patch, :delete, :options],
        credentials: true # here
      end
    end

Now Rails (API) on localhost:3001 can recieve requests from React on localhost:3000 and surely return the certain response to the client (browser).

Tomoya

Reference:

Ruby on Rails+ReactでCRUDを実装してみた
What is CORS | Codecademy
CORSがよくわからないので解説してみた&Rails APIでのCORS設定


Relative Posts:

CORS通信とは

May 11, 2020

How to start React × Rails(API) project with Docker

May 10, 2020

Tomoya Sonokui

To output what I learn from things, and brush up both English & Japanese writing skills. 日々感じたことや学んだことを日本語と英語でアウトプットするための技術系ブログ

RotateLinkImg-iconRotateLinkImg-iconRotateLinkImg-icon