cyu / rack-cors

Rack Middleware for handling Cross-Origin Resource Sharing (CORS), which makes cross-origin AJAX possible.
MIT License
3.27k stars 262 forks source link

Access-Control-Request-Method is missing #205

Closed coding-bunny closed 4 years ago

coding-bunny commented 4 years ago

Hello,

I'm trying to understand why the rack-cors gem is not exposing the Access-Control-Request-Method header?

I've configured this as follows:

CORS_HEADERS = %w[ETag Access-Control-Request-Method].freeze
CORS_READ_METHODS = %i[get options head].freeze
CORS_METHODS = %i[get post put options patch delete head].freeze

config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins(/^(http(s)*\:\/\/)*(.*\.|)my_domain\.com$/)
        resource("*/api/v3/*", credentials: true, headers: :any, methods: CORS_METHODS, expose: CORS_HEADERS)
        resource("*", credentials: true, headers: :any, methods: CORS_READ_METHODS, expose: CORS_HEADERS)
      end

      if Rails.env.development? || Rails.env.test?
        allow do
          origins(/^(.*\:\/\/)*(.*\.|)localhost(\:\d+)*$/)
          resource("*", headers: :any, methods: CORS_METHODS, expose: CORS_HEADERS)
        end

        allow do
          origins(/^(.*\:\/\/)*(.*\.|)example\.com(\:\d+)*$/)
          resource("*", headers: :any, methods: CORS_METHODS, expose: CORS_HEADERS)
        end

        allow do
          origins(/(.*\:\/\/)*(.*\.|)\w*\.pdev(\:\d+)*/)
          resource("*", headers: :any, methods: CORS_METHODS, expose: CORS_HEADERS)
        end
      end
    end

However, when making test request, the Access-Control-Request-Method is never in the response:

curl -D - -I -X OPTIONS -H "Origin: https://my_domain.com" -H "Access-Control-request-Method: GET" localhost:3000/api/v3/products

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://my_domain.com
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, PATCH, DELETE, HEAD
Access-Control-Expose-Headers: ETag, Access-Control-Request-Method
Access-Control-Max-Age: 7200
Access-Control-Allow-Credentials: true
Transfer-Encoding: chunked

I can see it's in the expose-header from the configuration, but the actual header is not exposed.

cyu commented 4 years ago

Access-Control-Request-Method is a request header - it is given as part of the preflight request coming into the server. As a response, CORS returns the allowed request method for that resource as Access-Control-Allow-Methods.

coding-bunny commented 4 years ago

Gotcha, so it will never show up in the response, I just tell the server how I want to request the resource, and check the reply whether it's allowed or not.

Then I know how to write specs for this now, thank you :)