I'm trying to implement google places api in my rails app.
This is the error I'm getting when trying to use the function that is fetching the data from the ajax request:
XMLHttpRequest cannot load . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I'm using rack-cors gem and I've added this snippet into my config/application.rb file:
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
This is the ajax request from my view (coffeescript):
$.ajax
url: url
dataType: "json"
type: "GET"
I've added this part to my application_controller
before_filter :cors_preflight_check
after_filter :cors_set_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-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = "1728000"
end
def cors_preflight_check
if request.method == :options
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
and this, to my routes file
match '*path' => 'application#cors_preflight_check', :via => :options
I've noticed that "cors_preflight_check" method is not triggered by my request. (I make the AJAX request when I click a certain link in my view)
and I've noticed that my request headers remain unchanged.
(Access-Control-Allow-Origin is not added to request headers)
jsonp is not an option because it's not supported by places api
Tried everything that's written in these threads:
- https://github.com/cyu/rack-cors/issues/33
- Can't get rack-cors working in rails application (config.middleware.insert 0, Rack::Cors do)
- https://demisx.github.io/rails-api/2014/02/18/configure-accept-headers-cors.html
- POST Method not working in rack-cors rails 4 (adding before & after actions in the app controller)
- Add custom response header with Rack-cors and Grape (using :expose key)