[Rails] Dealing with CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

During the recent Rails Api Project, I met the CORS problem as below.

I found two solutions for fixing the problem.

  1. To get rack-cors working, add the gem ‘rack-cors’ to the Gemfile or uncomment the gem and run bundle install.

2 -1. Add the following to config/application.rb inside class Application < Rails::Application:

2–2. Or add the following file into the ‘config/initializers’ folder or uncomment.

Resources

student at Flatiron School