【问题标题】:Origin http://localhost is not allowed by Access-Control-Allow-Origin Rails 3Access-Control-Allow-Origin Rails 3 不允许来源 http://localhost
【发布时间】:2012-12-28 02:48:57
【问题描述】:

关注这个问题How to set access-control-allow-origin in webrick under rails?,我可以GETPOSTlocalhostlocalhost:3000 em>

但是,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

知道怎么解决吗?

【问题讨论】:

    标签: ruby-on-rails cross-domain


    【解决方案1】:

    * 不是 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 请求。这是为了允许 CORS 预检请求,在发出 PUT 或 DELETE 请求时需要这些请求。

    【讨论】:

    • 如果 * 不是标头“access-control-allow-methods”的有效值,您能否解释一下为什么 Chrome 在使用上述代码跨域请求资源时不再引发跨域错误提问者问?他的代码似乎对我有用,我试图了解什么是“正确”的做法,以及为什么
    • @n00b 上面的代码仅适用于 CORS 预检请求。如果您的请求是简单的 CORS 请求,则没有预检。
    【解决方案2】:

    这个解决方案 (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-04-09
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2014-07-14
      • 1970-01-01
      相关资源
      最近更新 更多