Allow API Requests From Anywhere In Rails

Posted by Weston Ganger on November 19, 2015

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:

Posted in Rails and Tagged with cors rails cross-origin 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts