Allow API Requests From Anywhere In Rails

Posted By Weston Ganger

If you've got to configure a public API or with another javascript app, CORS is something you will come across.

If you want a more configurable and standard way of doing this, then use the gem rack-cors

Otherwise you can do it in a quick and dirty way using a before_filter. Im going to put mine in the application controller to apply to the whole site, you may want to restrict this in specific controllers.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_filter :apply_cors_policy


  def apply_cors_policy
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'


Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:November 19, 2015