How do I add CORS to a compojure-api app?

大憨熊 提交于 2021-02-09 09:36:17

问题


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]))

回答1:


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.



来源:https://stackoverflow.com/questions/52745107/how-do-i-add-cors-to-a-compojure-api-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!