2017-04-08 90 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