If you enjoy this article you may be interested in the book I am working on called Building and Deploying Crypto Trading Bots.
By default Rails blocks cross origin resource sharing requests (CORs) to protect applications from malicious requests. However, when developing a SPA frontend using a framework like React or Vue.JS and a headless Rails API backend we will need to make requests from a different port serving our app on our local host. To allow these requests to reach our server, we will add a piece of middleware as a gem called rack-cors
.
This gem will enable us to whitelist request origins and their methods. Add the rack-cors
(1.1.1) gem to your Gemfile then run bundle install afterwords. Once the gem is installed, open, and uncomment the config/initializer/rack-cors.rb
file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS)
# in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cor
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:8080'
resource '*',
headers: :any,
methods: [:get,
:post,
:put,
:patch,
:delete,
:options,
:head]
end
end
The Rails defaults are reasonable so the only modification required is allowing requests from the origin localhost:8080
(the port of your frontend app) instead of example.com.