1

我有一个 Rails 3 应用程序。在 API 开发过程中,由于CORS,我遇到了一些意外OPTIONS请求的麻烦。所以我决定使用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-cors500 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
4

1 回答 1

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
于 2015-12-04T19:13:07.923 回答