Skip to content

Instantly share code, notes, and snippets.

@leordev
Created August 14, 2016 22:17
Show Gist options
  • Save leordev/35bee2e7dfde38ced6b1f5236cc45c0d to your computer and use it in GitHub Desktop.
Save leordev/35bee2e7dfde38ced6b1f5236cc45c0d to your computer and use it in GitHub Desktop.
(ns api-project.cors)
(def cors-headers
"Generic CORS headers"
{"Access-Control-Allow-Origin" "*"
"Access-Control-Allow-Headers" "*"
"Access-Control-Allow-Methods" "GET"})
(defn preflight?
"Returns true if the request is a preflight request"
[request]
(= (request :request-method) :options))
(defn all-cors
"Allow requests from all origins - also check preflight"
[handler]
(fn [request]
(if (preflight? request)
{:status 200
:headers cors-headers
:body "preflight complete"}
(let [response (handler request)]
(update-in response [:headers]
merge cors-headers )))))
@bhurlow
Copy link

bhurlow commented Aug 14, 2016

🍨

@ccann
Copy link

ccann commented Sep 14, 2016

FYI, since I just got burned by this: wildcard "*" for "Access-Control-Allow-Headers" might not be supported by all browsers see here http://stackoverflow.com/questions/13146892/cors-access-control-allow-headers-wildcard-being-ignored

@alehatsman
Copy link

love it

@jtackett
Copy link

Searched for a while and this worked for me also. Thank you!

@andyfry01
Copy link

Thank you so much for this gist. I've had a maddening time getting ring-cors to do ... anything at all based on the documented example, and this got my CORS settings for an http-kit/compojure server working finally!

@kentbull
Copy link

Like @andyfry01 it was maddening for me to get ring-cors working. Thank you for this Gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment