gpt4 book ai didi

clojure - 如何在compojure中启用跨域请求?

转载 作者:行者123 更新时间:2023-12-02 10:18:53 25 4
gpt4 key购买 nike

我一直在尝试很多方法来实现这一点,我认为正确的方法是设置这样的 header (我在nodejs/express应用程序中这样做):

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

我写了这样的函数:

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

我用curl -v对其进行了测试,发现响应中只有最后一个值真正存在。我所需要的只是在 header 中写入多个键值对。怎么做?或者也许有另一种方法可以解决问题。

最佳答案

请记住,assoc-in 仍然不会修改原始结构:响应 将始终具有与(处理程序请求)相同的值 .

(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" "*"}}

关于clojure - 如何在compojure中启用跨域请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27592965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com