r0man / ring-cors

Ring middleware for Cross-Origin Resource Sharing.
http://github.com/r0man/ring-cors
169 stars 44 forks source link

access-control-allow-origin does not show in response headers #1

Open alolis opened 11 years ago

alolis commented 11 years ago

Hello,

I am using compojure and I wanted to allow origin from anywhere for the development process of my app so i added ring-cors like the example shows but if i look at the response headers on my chrome developer tools, i do not see the header set.

Does this middleware still works or is it abandoned?

Thanks for your time

alolis commented 11 years ago

I checked the code and there is no "origin" inside the headers which is used to get the origin here: https://github.com/r0man/ring-cors/blob/master/src/ring/middleware/cors.clj#L7

This is what i see inside the headers of a test request:

{"accept" "/", "accept-encoding" "gzip,deflate,sdch", "accept-language" "en-US,en;q=0.8,el;q=0.6", >"connection" "keep-alive", "cookie" "PHPSESSID=aj198ujlvi9ag1ntrvj5m8e160; rock_format=json", "host" >"localhost:3000", "user-agent" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) >Chrome/27.0.1453.93 Safari/537.36"}

Also, it would be nice if allow-request? supported the use of wildcard (*).

bripkens commented 10 years ago

The problem is that CORS headers are only added when the request is allowed. They should probably be present for every request.

For development purposes and requests that do not require credentials the following CORS middleware is sufficient.

(defn wrap-cors
  "Allow requests from all origins"
  [handler]
  (fn [request]
    (let [response (handler request)]
      (update-in response
                 [:headers "Access-Control-Allow-Origin"]
                 (fn [_] "*")))))
bhurlow commented 10 years ago

if you're trying to go "all-the-way" you can do something like this:


(def cors-headers 
  { "Access-Control-Allow-Origin" "*"
    "Access-Control-Allow-Headers" "Content-Type"
    "Access-Control-Allow-Methods" "GET,POST,OPTIONS" })

(defn all-cors
  "Allow requests from all origins"
  [handler]
  (fn [request]
    (let [response (handler request)]
      (update-in response [:headers]
        merge cors-headers ))))

note that you'll need some way of handling OPTIONS requests.

leordev commented 8 years ago

@bhurlow awesome catch... merging yours with a pre-flight it's even better... https://gist.github.com/leordev/35bee2e7dfde38ced6b1f5236cc45c0d 😆