7

按照这个问题How to set access-control-allow-origin in webrick under rails? GET,我可以POSTlocalhostlocalhost: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

知道如何解决吗?

4

2 回答 2

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"

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

于 2013-01-15T03:53:38.823 回答
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]

我希望它有帮助

于 2013-06-21T17:52:17.523 回答