首页 文章

在Compojure中使用嵌套的defroutes时无法访问表格参数

提问于
浏览
1

我无法从POST请求中访问表单参数 . 我已经尝试了我在文档中看到的中间件和配置选项的每个组合,在SO等等(包括不推荐的compojure / handler选项),我仍然无法看到参数 . 我确定我错过了一些非常明显的东西,所以任何建议(无论多么轻微)都会非常感激 .

这是我的最新尝试,其中我尝试使用site-defaults中间件并禁用默认提供的防伪/ 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))

更新:参数似乎被外部 defroutes 吞噬:

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

所以,我的问题现在变成:如何将参数线程化到嵌套的 defroutes

我的临时解决方案基于this解决方案,但Steffen Frank's更简单 . 我会尝试并跟进 .

更新2:

在尝试实现两个当前答案提供的建议时,我遇到了一个新问题:路由匹配过于激烈 . 例如鉴于以下情况,由于config-routes中的wrap-basic-authentication中间件,POST / to something失败并返回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)

3 回答

  • 0

    问题是,当您以这种方式定义路线时:

    (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 为不匹配的URL路径返回nil(例如,它不应该定义 not-found 路由) .

  • 2

    只是一个猜测,但你试过这个:

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

    您可能会发现以下帖子很有用 . 它讨论了混合api和app路由,以便它们不会相互干扰,并且避免将中间件从一个添加到toher等.Serving app and api routes with different middleware using Ring and Compojure

相关问题