在Compojure POST请求中缺少表单参数

时间:2011-05-17 20:31:36

标签: clojure compojure

我在以下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: {}

我无法弄清楚为什么title参数不在params地图中。

我正在使用Compojure 0.6.2。

4 个答案:

答案 0 :(得分:15)

你有没有考虑过这个:

  

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

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

我用我当前的设置尝试了你的例子并且它有效。我添加了以下内容:require [compojure.handler :as handler](handler/api routes)

答案 1 :(得分:15)

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

(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 - 中间件是功能

答案 2 :(得分:0)

你可以给出一个参数列表; compojure会自动将它们从POST / GET params中取出。如果你需要做更多复杂的事情,但我从未研究过如何做。例如,以下是4clojure代码中的代码段:

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

答案 3 :(得分:0)

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

相关问题