17

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

4 回答 4

16

你有没有考虑到这一点:

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

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

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

于 2011-05-17T21:22:16.430 回答
16

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

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

于 2011-11-20T03:54:26.783 回答
0

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

(POST "/problems/submit" [title tags description code]
  (create-problem title tags description code))
于 2011-05-17T20:43:00.843 回答
0

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

于 2012-11-17T19:20:55.267 回答