3

How can I add CORS to this code snippet?

(def app
    (api
        {:swagger {:ui   "/docs"
                   :spec "/swagger.json"}}

       (GET "/route-a" [] "a")
       (GET "/route-b" [] "b")
       (GET "/route-c" [] "c")))

I would like to use https://github.com/r0man/ring-cors and have tried this, but it did not seem to do anything. I would like to see the response header contain Access-Control-Allow-Origin but it is missing.

(-> (api
   {:swagger {:ui   "/docs"
              :spec "/swagger.json"}}

   (GET "/route-a" [] "a")
   (GET "/route-b" [] "b")
   (GET "/route-c" [] "c"))

  (wrap-cors :access-control-allow-origin #"http://localhost:81"
             :access-control-allow-headers ["Origin" "X-Requested-With"
                                        "Content-Type" "Accept"]
             :access-control-allow-methods [:get :put :post :delete :options]))
Freid001
  • 2,580
  • 3
  • 29
  • 60
  • 1
    I think you need allowed methods too – Alejandro C. Oct 10 '18 at 17:48
  • https://github.com/r0man/ring-cors/blob/fe44f9e11565b3e0eeb81c1fabebb6c29e3d077f/src/ring/middleware/cors.clj#L90 – nakiya Oct 11 '18 at 08:30
  • I added allowed methods but it still doesn't do anything – Freid001 Oct 11 '18 at 09:22
  • 1
    Works for me: if I run the API on localhost:3000 and execute `curl -vH "Origin: http://localhost:81" localhost:3000/route-a`, I get the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers in the output – Aleph Aleph Oct 11 '18 at 22:49

1 Answers1

2

The CORS-specific response headers are returned only if the request has an Origin header that matches the specified regex (when a request is made using XMLHttpRequest in browser, the Origin header is added automatically).

If you try:

curl -vH "Origin: http://localhost:81" localhost:3000/route-a

(assuming that your API is available on port 3000), you will see that the necessary response headers are added. AJAX requests from http://localhost:81 should also work.

Aleph Aleph
  • 5,215
  • 2
  • 13
  • 28