【问题标题】:Missing form parameters in Compojure POST requestCompojure POST 请求中缺少表单参数
【发布时间】:2011-08-27 13:29:06
【问题描述】:

我在以下 Compojure 示例中获取表单参数时遇到问题:

(ns hello-world
  (:use compojure.core, ring.adapter.jetty)
  (:require [compojure.route :as route]))

(defn view-form []
(str "<html><head></head><body>"
   "<form method=\"post\">"
   "Title <input type=\"text\" name=\"title\"/>"
   "<input type=\"submit\"/>"
   "</form></body></html>"))

(defroutes main-routes
  (GET "/" [] "Hello World")
  (GET "/new" [] (view-form))
  (POST "/new" {params :params} (prn "params:" params))
  (route/not-found "Not Found"))

(run-jetty main-routes {:port 8088})

提交表单时输出总是

params: {}

我不知道为什么标题参数不在 params 映射中。

我正在使用 Compojure 0.6.2。

【问题讨论】:

    标签: clojure compojure


    【解决方案1】:

    你可以只给出一个参数列表; compojure 将相应地自动将它们从 POST/GET 参数中取出。如果你需要做更复杂的事情,你可以,但我从来没有研究过如何做。例如,这是4clojure 代码中的一个 sn-p:

    (POST "/problems/submit" [title tags description code]
      (create-problem title tags description code))
    

    【讨论】:

    • 我也尝试过这种方式,但我只得到参数为零。
    【解决方案2】:

    您是否考虑到这一点:

    从 0.6.0 版开始,Compojure 不再向路由添加默认中间件。这意味着您必须将 wrap-params 和 wrap-cookies 中间件显式添加到您的路由中。

    来源:https://github.com/weavejester/compojure

    我用我当前的设置尝试了你的例子,它成功了。我包括以下内容:require [compojure.handler :as handler](handler/api routes)

    【讨论】:

    【解决方案3】:

    这是如何处理参数的一个很好的例子

    (ns example2
      (:use [ring.adapter.jetty             :only [run-jetty]]
        [compojure.core                 :only [defroutes GET POST]]
        [ring.middleware.params         :only [wrap-params]]))
    
    (defroutes routes
      (POST "/" [name] (str "Thanks " name))
      (GET  "/" [] "<form method='post' action='/'> What's your name? <input type='text' name='name' /><input type='submit' /></form>"))
    
    (def app (wrap-params routes))
    
    (run-jetty app {:port 8080})
    

    https://github.com/heow/compojure-cookies-example

    参见示例 2 - 中间件是功能

    【讨论】:

      【解决方案4】:

      这是一个截至 2012 年 11 月 17 日的可运行示例:

      【讨论】:

      • 我点击了你的链接,我只看到了一个 GET 路由,而这个问题是关于来自 POST 请求的表单参数。
      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 2021-08-12
      • 2012-08-29
      相关资源
      最近更新 更多