Rails, Backbone, PhoneGap, CORS (not allowed by Access-Control-Allow-Origin error)

I am creating a Phonegap application that uses backbone.js and backend. When creating new users, I get a CORS related error:

I run my PhoneGap web application on http://0.0.0.0:8000 ($ python -m SimpleHTTPServer) and run my Rails application in webrick on http://0.0.0.0:3000 {000 ($ rails server).

The problem occurs when trying to create a new "Spot" in Backbone like this (chrome js console):

 > s = new App.Models.Spot() (creates Spot) > s.save() (returns error Object) OPTIONS http://0.0.0.0:3000/spots.json 404 (Not Found) jquery-1.8.2.js:8416 XMLHttpRequest cannot load http://0.0.0.0:3000/spots.json. Origin http://0.0.0.0:8000 is not allowed by Access-Control-Allow-Origin. 

Here is my application controller:

 def set_access_control_headers headers['Access-Control-Allow-Origin'] = 'http://0.0.0.0:8000' headers['Access-Control-Request-Method'] = 'POST, GET' end 

I read a lot of articles, and the most I could get when I changed my .rb routes to include this:

 match '*all' => 'application#cor', :constraints => {:method => 'OPTIONS'} 

And in my application application_controller.rb

 def cor headers["Access-Control-Allow-Origin"] = "*" headers["Access-Control-Allow-Methods"] = %w{GET POST PUT DELETE OPTIONS}.join(",") headers["Access-Control-Allow-Headers"] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",") head(:ok) if request.request_method == "OPTIONS" end 

Adding a route and the cor method will allow me to save files, but I will get the same error when deleting entries.

I get the basic idea of โ€‹โ€‹CORS, I cannot access a server with a different domain than the source of my request. But how to fine-tune this using Rails, Backbone, Phonegap, it is not clear to me. Any help would be awesome, thanks!

+6
source share
1 answer

I follow this article ("CORS in Rails" section) and it works for me.

I change if request.method == :options to if request.method == 'OPTIONS' and add the PUT, DELETE methods to headers['Access-Control-Allow-Methods'] . Insted of '*' in Access-Control-Allow-Origin I have localhost: 8080 (I am running my application on nginx).

Hope this helps.

PD: Do you have filters (hooks) in your application controller?

+2
source

All Articles