2011-05-17 143 views
14

我在得到的形式参数在下面的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。

回答

14

你有没有考虑到这一点:

随着0.6.0版本的Compojure不再添加默认中间件路线。这意味着你必须明确地将wrap-params和wrap-cookies中间件添加到你的路由中。

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

我想你的榜样与我的当前设置和它的工作。我已经包括以下内容:require [compojure.handler :as handler](handler/api routes)

+1

'compojure.handler'已弃用。改为使用'ring.middleware.params'。 – 2015-12-23 09:32:01

+0

正确,并且这个答案给出了一个适用于我的示例:http://stackoverflow.com/a/8199332/3884713 – 2016-03-29 18:05:13

0

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

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

我也试过这种方式,但我只得到零参数。 – cretzel 2011-05-17 20:50:22

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