Access-Control-Allow-Origin Rails 3不允许使用origin http:// localhost

时间:2013-01-14 04:46:14

标签: ruby-on-rails cross-domain

关注此问题How to set access-control-allow-origin in webrick under rails?,我可以从 localhost GETPOST 本地主机:3000 即可。

但是,DELETEPUT

发生了错误

这是我允许跨域访问的方式

class ApplicationController < ActionController::Base
    protect_from_forgery
    before_filter :allow_cross_domain_access
    def allow_cross_domain_access
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Methods"] = "*"
    end
end

知道怎么解决吗?

2 个答案:

答案 0 :(得分:11)

*不是Access-Control-Allow-Methods响应标头的有效值。您需要列出实际方法:

response.headers["Access-Control-Allow-Methods"] = "GET, PUT, POST, DELETE"

此外,如果您的请求包含任何自定义请求标头,您还需要列出这些标头:

response.headers["Access-Control-Allow-Headers"] = "Content-Type, X-Requested-With"

最后请注意,您的控制器应该允许OPTIONS http请求。这是为了允许在发出PUT或DELETE请求时所需的CORS预检请求。

答案 1 :(得分:9)

此解决方案(http://www.tsheffler.com/blog/?p=428)适合我:

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
  if request.method == :options
    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'
    render :text => '', :content_type => 'text/plain'
  end
end

此外,您可能希望在所选方法中启用CORS:

before_filter :cors_preflight_check, :only => [ :my_method]
after_filter :cors_set_access_control_headers, :only => [ :my_method]

我希望它有所帮助