Rails Responds with 404 on CORS Preflight Options Request

前端 未结 7 1293
既然无缘
既然无缘 2020-12-10 00:42

I\'m creating a set of services using Rails 4, which I am consuming with a JavaScript browser application. Cross-origin GETS are working fine, but my POSTs are failing the p

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 00:59

    Here's a solution with the rack-cors gem, which you said you tried. As others have mentioned, you didn't give much detail in regards to which front-end framework you're using and what the actual request looks like. So the following may not apply to you, but I hope it helps someone.

    In my case, the gem worked fine until I used PUT (or PATCH or DELETE).

    If you look in your browser developer console, look at the request headers, and you should have a line like this:

    Access-Control-Request-Method: PUT
    

    The important thing to note is that the methods you pass to resource are for the Access-Control-Request-Method, not the Request Method that is to come after the pre-flight check.

    Note how I have :methods => [:get, :post, :options, :delete, :put, :patch] that will include all the methods I care about.

    Thus your entire config section should look something like this, for development.rb:

    # This handles cross-origin resource sharing.
    # See: https://github.com/cyu/rack-cors
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        # In development, we don't care about the origin.
        origins '*'
        # Reminder: On the following line, the 'methods' refer to the 'Access-
        # Control-Request-Method', not the normal Request Method.
        resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
      end
    end
    

提交回复
热议问题