使用lein-ring并将处理程序包装在函数中时,无效的防伪令牌吗?

问题描述 投票:0回答:1

使用Ring时,当POST请求都给出“无效的防伪令牌”时,我会感到莫名其妙的行为,但是当我将处理程序放在函数后面时,only会这样做。

所以,

(def app app-routes)

工作正常。

Whereas

(defn app [args] 
  (app-routes args))

引发POST请求的伪造错误。

最小代码示例。 :

(defroutes app-routes
  (GET "/login" request (fn [req]
                          (html5
                            [:body
                             [:div
                              [:form {:action "/login" :method "post"}
                               (anti-forgery-field)
                               [:input {:name "username"}]
                               [:input {:name "password"}]
                               [:button {:type "submit"} "submit"]]]])))

  (POST "/login" request (fn [req] "Yay!")))


; WORKS A-OK like this
(def app (-> app-routes (wrap-routes site-defaults)))

在我的project.clj中>

:plugins [[lein-ring "0.12.5"]]
:ring {:handler myapp.application/app

但是再次,如果我将其更改为函数:

(defroutes app-routes
  (GET "/login" request (fn [req]
                          (html5
                            [:body
                             [:div
                              [:form {:action "/login" :method "post"}
                               (anti-forgery-field)
                               [:input {:name "username"}]
                               [:input {:name "password"}]
                               [:button {:type "submit"} "submit"]]]])))

  (POST "/login" request (fn [req] "Yay!")))


; ALL POST REQUESTS FAIL 
(defn app [args] 
  (let [handler (-> app-routes (wrap-routes site-defaults)))]
    (handler args)))

所有发布请求均由于伪造令牌而失败。所有GET请求都可以正常工作。

[陌生人:我想也许它不喜欢重新初始化,所以我把它塞进了atom使其更像单身人士

(def handler (atom nil))
(defn app [args] 
  (swap! handler #(when (nil? %)
                    (-> app-routes
                        (wrap-defaults site-defaults))))
  (@handler args))

现在GET和POST请求按预期方式工作。除了现在的包装重新加载(上面未显示)之外,都会引发异常!

我不知道为什么会这样,并且完全无法调试。谁能给我一些启示?

编辑:

有关为什么要尝试全部包装的上下文:我希望能够连接依赖项(例如数据库连接),然后将其注入到路由所使用的控制器中。

使用Ring时,当POST请求都给出“无效的防伪令牌”时,我会感到莫名其妙的行为,但是只有当我在函数后面有处理程序时,才这样做。因此,(def app app-routes)...

clojure ring
1个回答
0
投票

我不是wrap-routes的专家,但是有明确的线索可以解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.