1

I have a Rails 3 app. And I got some troubles with unexpected OPTIONS requests due to CORS during API development. So I decided to use the 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

I send AJAX request with following jQuery code:

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

It worked well before using rack-cors (in localhost <-> localhost scenario). But after installing rack-cors I caught 500 error and found that line in the logs:

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

It seems as if Rails ignores json content type requirement. What should I do to fix that?

Request headers:

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

Response headers:

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
sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
petRUShka
  • 9,231
  • 12
  • 54
  • 86

1 Answers1

0

Try moving to to 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
CWitty
  • 4,269
  • 3
  • 20
  • 34