Access-Control-Allow-Origin Rails项目,跨域,无路由匹配[OPTIONS]

Big*_*bie 2 ruby-on-rails cors ruby-on-rails-3

我正在我的Rails项目中实现一个API:我有一个示例HTML页面来测试我在rails网站上的实现...我无法更改发送请求的站点上的编码.(下面的代码).我必须让我的rails项目接受请求.

我把它包含在我的ApplicationController中

  before_filter :allow_cross_domain_access
  def allow_cross_domain_access
    response.headers["Access-Control-Allow-Origin"] = '*'
    response.headers["Access-Control-Allow-Methods"] = "GET, PUT, POST, DELETE, OPTIONS"
  end
Run Code Online (Sandbox Code Playgroud)

当我用这个发布到我的网站时,我得到

XMLHttpRequest cannot load http://192.168.1.65:3000/post_everywhere/0/loads. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404
Run Code Online (Sandbox Code Playgroud)

rails控制台显示:

  Started OPTIONS "/post_everywhere/0/loads" for 192.168.1.184 at 2015-02-02 09:20:42 -0600
  2015-02-02 09:20:42 FATAL --
  ActionController::RoutingError (No route matches [OPTIONS] "/post_everywhere/0/loads"):
Run Code Online (Sandbox Code Playgroud)

事情是我想要它POST不使用OPTIONS

我设置我的路线像这样:

  resources :post_everywhere do
    post :create_account
    post :update_account
    post :validate_account
    post :loads
    post :trucks
  end
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它对我不起作用,因为它正在寻找一个模板:

match 'post_everywhere/0/loads' => 'post_everywhere#loads', :via => [:get, :post, :options]
Run Code Online (Sandbox Code Playgroud)

我无法更改的代码: 这是其他网站向我发送信息的方式.

function postLoad(remove) {
    try {
        var postToURL = document.getElementById("postToURL").value;
        var xmlhttp;
        if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
        else if (window.ActiveXObject) xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
        else alert("Your browser does not support XMLHTTP!");
        xmlhttp.open("POST", postToURL, true);
        xmlhttp.setRequestHeader('Content-Type', "text/xml");
        xmlhttp.send(formatLoadPost(remove));
    }
    catch(e) { alert(e); }
}
function formatLoadPost(remove) {
    try {
        postXML = "<PELoadPostings><PostingAccount>";
        postXML += "<UserName>" + document.getElementById("login").value + "</UserName>";
        postXML += "<Password>" + document.getElementById("password").value + "</Password>";
        postXML += "<ContactName>" + document.getElementById("contactName").value + "</ContactName>";
        postXML += "<ContactPhone>" + document.getElementById("contactPhone").value + "</ContactPhone>";
        postXML += "<ContactFax>" + document.getElementById("contactFax").value + "</ContactFax>";
        postXML += "<ContactEmail>" + document.getElementById("contactEmail").value + "</ContactEmail>";
        postXML += "<CompanyName>" + document.getElementById("companyName").value + "</CompanyName>";
        postXML += "<UserID>" + document.getElementById("userID").value + "</UserID>";
        if (remove) postXML += "</PostingAccount><RemoveLoads>" + document.getElementById("loadData").value + "</RemoveLoads></PELoadPostings>";
        else postXML += "</PostingAccount><PostLoads>" + document.getElementById("loadData").value + "</PostLoads></PELoadPostings>";
        return postXML;
    }
    catch(e) { alert(e); }
}
Run Code Online (Sandbox Code Playgroud)

我已经实现了你的解决方案,现在我得到了这个:

Started OPTIONS "/api/v3/post_everywhere/loads" for 192.168.1.184 at 2015-02-02 11:40:33 -0600
2015-02-02 11:40:33 INFO -- Processing by Api::V3::PostEverywhereController#loads as */*
2015-02-02 11:40:33 WARN -- WARNING: Can't verify CSRF token authenticity
2015-02-02 11:40:34 INFO --   Rendered text template (0.0ms)
2015-02-02 11:40:34 INFO -- Filter chain halted as :cors_preflight_check rendered or redirected
2015-02-02 11:40:34 INFO -- Completed 200 OK in 131ms (Views: 11.9ms | ActiveRecord: 0.0ms)
Filter chain halted as :cors_preflight_check rendered or redirected
Run Code Online (Sandbox Code Playgroud)

控制台日志

 XMLHttpRequest cannot load http://192.168.1.65:3000/api/v3/post_everywhere/loads. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
Run Code Online (Sandbox Code Playgroud)

我不想要一个文本模板我想要拉入参数...

但它没有显示params(XML)

  def loads
    puts params
    render json: { success: true }
  end
Run Code Online (Sandbox Code Playgroud)

我终于弄明白了如何使用XML doc ...

  def loads
    xml_doc = Nokogiri::XML(request.body.read)
    render json: { success: true }
  end
Run Code Online (Sandbox Code Playgroud)

Sli*_*pan 7

CORS要求您在接受任何其他请求之前响应OPTIONS.这个要点给出了如何做到这一点的一个例子.重要的是

before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
  headers['Access-Control-Max-Age'] = "1728000"
end

def cors_preflight_check
  if request.method == 'OPTIONS'
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
    headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token'
    headers['Access-Control-Max-Age'] = '1728000'

    render :text => '', :content_type => 'text/plain'
  end
end
Run Code Online (Sandbox Code Playgroud)

这将使用方法'OPTIONS'捕获任何请求,并使用正确的标头和没有内容进行响应.然后客户端应用程序可以发送一个帖子,该帖子将根据您的routes.rb文件进行路由.另见维基百科的条目