CORS stands for Cross-Origin Resource Sharing. CORS manages requests that occur between decoupled applications, or from another "origin". Browsers have security built in to protect users from submitting their data to servers that they are not intending to, so we have to tell the frontend that the backend is indeed the correct place for it to be communicating with.
- can define CORS
- can enable cross-origin resource sharing in an API
- CORS
The last bit of housekeeping we need to do on the backend is enable our Rails application to accept requests from the React application.
We need to update the application controller to allow requests from applications outside the Rails application.
To do this, we add a line to the ApplicationController:
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
end
CORS which stands for Cross-Origin Resource Sharing defines what external request can be made to our Rails API. Our React frontend and Rails backend applications are running on two different servers. We have to tell the Rails API that (while in development) it is okay to accept requests from any outside domain.
CORS can be added to our application by doing three things:
- Adding this line of code to the Gemfile:
gem 'rack-cors', :require => 'rack/cors'
- Add a file to the
config/initializers
directory namedcors.rb
and add the following code to the new file:
config/initializers/cors.rb
# 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-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*' # <- change this to allow requests from any domain while in development.
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
- Run the command $
bundle
from the command line to update the dependencies.
That's it! We can now accept POST, PUT, and DELETE requests in our server side application.
When you take your app to production, you'll want to change the wildcard *
to the URL that your frontend app is served from.