Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS in Rails 4 App

Tags:

I'm just about to pull my hair out... I've been trying to enable CORS in this Rails app since the morning and it just doesn't work. I've tried this, using Rack Cors Gem, this answer and this post all without success.

Can someone point me in the right direction?

Here's my js:

      var req = new XMLHttpRequest();        if ('withCredentials' in req) {             // req.open('GET', "https://api.github.com/users/mralexgray/repos", true);             req.open('GET', "http://www.postcoder.lc/postcodes/" + value, true);             // Just like regular ol' XHR             req.onreadystatechange = function() {                 if (req.readyState === 4) {                     if (req.status >= 200 && req.status < 400) {                         // JSON.parse(req.responseText) etc.                         console.log(req.responseText);                     } else {                         // Handle error case                     }                 }             };             req.send();         } 

When I try this url (from an external client): https://api.github.com/users/mralexgray/repos that works ok, I'm assuming the problem is with my Rails API. Am I wrong?

EDIT: Currently I have this in my controller:

skip_before_filter :verify_authenticity_token before_filter :cors_preflight_check after_filter :cors_set_access_control_headers  # For all responses in this controller, return the CORS access control headers. def cors_set_access_control_headers   headers['Access-Control-Allow-Origin'] = '*'   headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'   headers['Access-Control-Max-Age'] = "1728000" end  # If this is a preflight OPTIONS request, then short-circuit the # request, return only the necessary headers and return an empty # text/plain.  def cors_preflight_check   headers['Access-Control-Allow-Origin'] = '*'   headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'   headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'   headers['Access-Control-Max-Age'] = '1728000' end 
like image 226
WagnerMatosUK Avatar asked Apr 20 '15 14:04

WagnerMatosUK


People also ask

How do I enable CORS rails?

Using rack-cors You need to inform Rails which origin it should allow. To do that, you need to create a new initializer for your application. This configuration will only allow HTTP POST calls to /order endpoint and all HTTP methods to any other endpoint. You need to pay close attention to the origins parameter.

What is rack CORS in rails?

Rack CORS Middleware. Rack::Cors provides support for Cross-Origin Resource Sharing (CORS) for Rack compatible web applications. The CORS spec allows web applications to make cross domain AJAX calls without using workarounds such as JSONP.

How do I enable CORS in REST API?

Enable CORS support on a REST API resourceSign in to the API Gateway console at https://console.aws.amazon.com/apigateway . Choose the API from the APIs list. Choose a resource under Resources. This will enable CORS for all the methods on the resource.

Is CORS enabled by default?

CORS is off by default for security purposes.


2 Answers

You should use rack cors

It provides a nice DSL, to use in your config/application.rb, instead of the messy header work and before filters.

A very permissive would be as follows, but of course, you'll have to tailor it a bit.

use Rack::Cors do   allow do     origins '*'     resource '*', headers: :any, methods: :any   end   end 
like image 185
apneadiving Avatar answered Oct 27 '22 01:10

apneadiving


Rack::Cors provides support for Cross-Origin Resource Sharing

Steps to enable rackcors :

  1. Add this gem to your Gemfile:

    gem 'rack-cors'

  2. Add the code below to config/application.rb

If you are using Rails 3/4:

config.middleware.insert_before 0, "Rack::Cors" do   allow do     origins '*'     resource '*', :headers => :any, :methods => :any   end end 

If you are using Rails 5:

config.middleware.insert_before 0, Rack::Cors do   allow do     origins '*'     resource '*', headers: :any, methods: :any   end end 
like image 21
errakeshpd Avatar answered Oct 27 '22 01:10

errakeshpd