rack-cors gem changes接受从json到html的标题

时间:2015-12-04 18:16:38

标签: jquery ruby-on-rails ajax cors rack-cors

我有一个Rails 3应用程序。在API开发过程中由于unexpected OPTIONS requests导致CORS遇到了一些麻烦。所以我决定使用rack-cors gem。

config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '/api/*', headers: :any,
                       methods: [:get, :post, :put, :options]
  end
end

我发送带有以下jQuery代码的AJAX请求:

$.ajax({
  contentType: "application/json; charset=utf-8",
  type: 'POST', dataType: 'json', url: url, data: JSON.stringify(data)
}).done(success).fail(fail);

在使用rack-cors之前(在localhost <-> localhost场景中),它运作良好。但在安装rack-cors之后,我抓住了500 error并在日志中找到了该行:

Started POST "/api/my_resource/" for 127.0.0.1 at 2015-12-04 20:34:00+0300
Processing by Api::MyResourceController#create as HTML

似乎Rails忽略了json内容类型要求。我该怎么做才能解决这个问题?

请求标题:

POST /api/my_resource/ HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: ru,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Content-Type: application/json; charset=utf-8
Content-Length: 870
Origin: null
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

回复标题:

HTTP/1.1 500 Internal Server Error 
Content-Type: text/html; charset=utf-8
Content-Length: 963
X-Request-Id: e4150020dffb0fcc34cf04e134584b06
X-Runtime: 0.380448
access-control-allow-origin: null
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Max-Age: 1728000
Access-Control-Allow-Credentials: true
Vary: Origin
X-Rack-CORS: hit
Server: WEBrick/1.3.1 (Ruby/2.1.4/2014-10-27)
Date: Fri, 04 Dec 2015 17:30:10 GMT
Connection: Keep-Alive

1 个答案:

答案 0 :(得分:0)

尝试转到application.rb

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :put, :patch, :delete, :options, :head]
  end
end