2017-04-08 89 views
1

使用嵌套defroutes當我無法從POST請求訪問形式參數訪問形式PARAMATERS。我已經嘗試了我在文檔中看到的所有中間件和配置選項的組合,包括已棄用的compojure /處理程序選項等,但仍無法查看參數。我確信我錯過了一些非常明顯的東西,所以任何建議(無論多麼微不足道)都將不勝感激。無法在的Compojure

這裏是我的最新嘗試,其中我嘗試使用站點默認中間件和禁用默認提供的防僞/ CSRF保護。 (我知道這是一個壞主意。)但是,當我嘗試在Web瀏覽器中查看相關頁面時,瀏覽器嘗試下載頁面,就好像它是一個無法呈現的文件。 (有趣的是,使用curl時按預期的方式呈現頁面。)

以下是最新的嘗試:

(defroutes config-routes* 
    (POST "/config" request post-config-handler)) 

(def config-routes 
    (-> #'config-routes* 
    (basic-authentication/wrap-basic-authentication authenticated?) 
    (middleware-defaults/wrap-defaults (assoc middleware-defaults/site-defaults :security {:anti-forgery false})))) 

以前的嘗試:

(def config-routes 
    (-> #'config-routes* 
    (basic-authentication/wrap-basic-authentication authenticated?) 
    middleware-params/wrap-params)) 

UPDATE: 的參數似乎被吞噬外部defroutes

(defroutes app-routes 
    (ANY "*" [] api-routes) 
    (ANY "*" [] config-routes) 
    (route/not-found "Not Found")) 

所以,我的問題現在變成:我怎樣才能通過嵌套defroutes線程參數?

我的臨時解決基於this解決方案,但Steffen Frank's要簡單得多。我會嘗試並跟進。

更新2:

在努力落實兩國目前的答案提供的建議,我遇到一個新的問題:路由匹配是過於心急。例如鑑於以下情況,由於配置路由中的wrap-basic-authentication中間件,發送至/某些內容的POST會失敗並顯示401響應。

(defroutes api-routes* 
    (POST "/something" request post-somethings-handler)) 

(def api-routes 
    (-> #'api-routes* 
    (middleware-defaults/wrap-defaults middleware-defaults/api-defaults) 
    middleware-json/wrap-json-params 
    middleware-json/wrap-json-response)) 

(defroutes config-routes* 
    (GET "/config" request get-config-handler) 
    (POST "/config" request post-config-handler)) 

(def config-routes 
    (-> #'config-routes* 
    (basic-authentication/wrap-basic-authentication authenticated?) 
    middleware-params/wrap-params)) 

(defroutes app-routes 
    config-routes 
    api-routes 
    (route/not-found "Not Found")) 

(def app app-routes) 

回答

1

只是一個猜測,但你嘗試過這樣的:

(defroutes app-routes 
    api-routes 
    config-routes 
    (route/not-found "Not Found")) 
+0

謝謝,這是一個非常乾淨的解決方案。我結束了使用[this](http:// stackoverflow。com/a/28017586/382982)的方法,但會給這個嘗試。 – pdoherty926

+0

這工作...有點。如果'api-routes'在列表中首先出現,它會匹配/吞嚥請求,然後我回到我開始的位置。我的嵌套defroutes都沒有'找不到'處理程序,所以我很困惑,爲什麼會這樣。 – pdoherty926

2

的問題是,當你以這種方式定義您的路線:

(defroutes app-routes 
    (ANY "*" [] api-routes) 
    (ANY "*" [] config-routes) 
    (route/not-found "Not Found")) 

則任何請求都將被匹配通過api-routes,只要它返回非零響應。因此api-routes不會吞噬您的請求參數,而是竊取整個請求。

相反,你應該定義你的app-routes爲(首選的解決方案):

(defroutes app-routes 
    api-routes 
    config-routes 
    (route/not-found "Not Found")) 

或確保您api-routes返回nil,提供無與倫比的URL路徑(例如,它不應該有定義not-found路線)。

+0

感謝您將此放在一起。請參閱我對Steffen答案的迴應,但「首選解決方案」似乎與順序有關,這是我想避免的。當'api-routes'出現但沒有找到匹配時,我是否需要以某種方式顯式地「返回無匹配的URL路徑」? – pdoherty926

+0

很難判斷你是否不共享'api-routes'的實現。如果路由與請求不匹配,'defroutes'將創建一個處理函數,返回'nil'。看起來你的'api-routes'匹配你認爲不應該的請求。 –

+0

我已經使用基於最新迭代的示例更新了我的問題。儘管如此,我擔心我已經開始與「這是一個很好的問題」的指導原則發生衝突。 – pdoherty926