rigdonmr rigdonmr - 6 months ago 67
CoffeeScript Question

Rails: where to enable Access-Control-Allow-Origin

I'm trying to load a link in my coffeescript file like so:

$.ajax hobby.link,
type: 'GET'
dataType: 'html'
error: (jqXHR, textStatus, errorThrown) ->
console.log "AJAX Error"
success: (data, textStatus, jqXHR) ->
console.log "Successful AJAX call"

and have installed

gem 'rack-cors', :require => 'rack/cors'

and added

config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]

to my application.rb, but everytime I get

XMLHttpRequest cannot load http://www.example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

What else do I need to do to make these loads work?

Note that I'm currently performing that ajax call to three different links in a row.


Rack::Cors deals with allowing or denying CORS for your own website and domain. It cannot affect the CORS configuration for any other domain.

For example, your website might be http://example.com, and you're trying to send an AJAX request to http://example.net. Since example.net is not under your control, you don't control its CORS settings, and neither does Rack::Cors. This means that if example.net has disallowed AJAX requests, you can't do anything about it.

Talk to the administrator of the service you're trying to call, and see if you can persuade them to allow AJAX requests (at least from your domain).