Rails的,骨干,的PhoneGap,CORS(而不是允许访问控制 - 允许 - 产地误差)误差、骨干、产地、访问控制

2023-09-10 17:18:44 作者:相关昵称推荐>>

我建立的一个PhoneGap的应用程序使用Backbone.js的和Rails的后端。在创建新用户,我得到一个CORS相关的错误:

I'm building a Phonegap app in that uses backbone.js and a Rails backend. While creating new users, I am getting a CORS related error:

我在 http://0.0.0.0:8000 ($蟒蛇-m SimpleHTTPServer)上运行我的PhoneGap的Web应用程序,并在运行我的Rails应用程序的WEBrick http://0.0.0.0:3000 ($导轨服务器)。

I am running my PhoneGap web app on http://0.0.0.0:8000 ($ python -m SimpleHTTPServer), and running my Rails app in webrick on http://0.0.0.0:3000 ($ rails server).

试图在骨干网这样的(铬JS控制台)创建一个新的点,当问题发生:

The problem happens 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

我看了许多文章,并修改我的routes.rb中包含这个时候,最远沿我能得到的是:

I have read numerous articles, and the furthest along I could get was when modifying my routes.rb to include this:

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

在我application_controller.rb

And in my 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 the route and the 'cor' method will then allow me to make saves, but, I will have the same error when deleting records.

我得到CORS的基本思路,我不能访问服务器使用不同的域比我要求的起源。但究竟如何设置此使用Rails,骨干,PhoneGap的,就是我也不清楚。任何帮助将是真棒,谢谢!

I get the basic idea of CORS, I can't access a server with a different domain than that of the origin of my request. But how exactly to set this up with Rails, Backbone, Phonegap, is not clear to me. Any help would be awesome, thanks!

推荐答案

我已经按照这文章(一节,在Rails的CORS),它为我工作。

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

更改如果request.method ==:选项如果request.method ==选项和添加put方法,DELETE以标题[访问控制 - 允许 - 方法'] 。在 insted的*访问控制 - 允许 - 原产地我本地主机:8080(我跑我的nginx的应用程序)

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

希望这会有所帮助。

PD:在您的应用控制器你有过滤器(钩)

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