How to include cross origin queries in compojure?

I tried to use many methods to implement this, and I thought that the correct way is to set such headers (I did this in the nodejs / express application):

"Access-Control-Allow-Origin"  "*"
"Access-Control-Allow-Methods" "GET,PUT,POST,DELETE,OPTIONS"
"Access-Control-Allow-Headers" "X-Requested-With,Content-Type,Cache-Control"

I wrote a function like this:

(defn allow-cross-origin
  "middleware function to allow cross origin"
  [handler]
  (fn [request]
    (let [response (handler request)]
      (do
        (assoc-in response [:headers "Access-Control-Allow-Origin"]  "*")
        (assoc-in response [:headers "Access-Control-Allow-Methods"] "GET,PUT,POST,DELETE,OPTIONS")
        (assoc-in response [:headers "Access-Control-Allow-Headers"] "X-Requested-With,Content-Type,Cache-Control")))))

(def handler (-> app wrap-params allow-cross-origin))

I tested it with curl -v and found that the answer has only the last value. All I need to do is write a few key-value pairs in the headers. How to do it? Or maybe there is another way to solve the problem.

+4
source share
1 answer

Remember that assoc-instill does not change the original structure: responseit will always have the same meaning as in (handler request).

(let [response {}]
   (assoc-in response [:headers "Access-Control-Allow-Origin"]  "*")
   (assoc-in response [:headers "Access-Control-Allow-Methods"] "GET,PUT,POST,DELETE,OPTIONS")
   (assoc-in response [:headers "Access-Control-Allow-Headers"] "X-Requested-With,Content-Type,Cache-Control"))
==> {:headers {"Access-Control-Allow-Headers" "X-Requested-With,Content-Type,Cache-Control"}}

, . , , assoc-in . :

(let [response {}]
 (-> response
     (assoc-in [:headers "Access-Control-Allow-Origin"]  "*")
     (assoc-in [:headers "Access-Control-Allow-Methods"] "GET,PUT,POST,DELETE,OPTIONS")
     (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With,Content-Type,Cache-Control")))
 => {:headers {"Access-Control-Allow-Headers" "X-Requested-With,Content-Type,Cache-Control", "Access-Control-Allow-Methods" "GET,PUT,POST,DELETE,OPTIONS", "Access-Control-Allow-Origin" "*"}}
+3

Source: https://habr.com/ru/post/1568544/


All Articles