我一直在尝试很多方法来实现这一点,我认为正确的方法是设置这样的标头(我在nodejs / express app中这样做了):
"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测试了它,发现只有最后一个值真的存在于响应中。我只需要在头文件中写入多个键值对。怎么做?或许还有另一种解决问题的方法。
答案 0 :(得分:3)
请注意,assoc-in
仍然不会修改原始结构:response
将始终具有与(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" "*"}}