我正在尝试更深入地研究 ring 并使用以下代码来查看请求映射中发生了什么:
(需要'[ring.adapter.jetty :as serv]) (需要'[ring.middleware.params :as wp]) (定义基本处理程序 [参数] {:代码 200 :输入“txt/html” :body (str 参数)}) (defn wp-handler [参数] ((wp/wrap-params base-handler) params)) (serv/run-jetty #'wp-handler {:port 8099})
当我想查看get
请求图上的查询数据时,它就在那里。假设我在http://localhost:8099/api/tasks/remove?hello=3
浏览器中输入,响应看起来像这样:
{:ssl-client-cert 无, :远程地址“127.0.0.1”, :方案:http, :request-method :get, :uri "/api/tasks/remove" :查询字符串“你好=3” .... 更多的 ....}
您可以看到“hello=3”在查询字符串中。
但是对于post
,响应有 :content-type "application/x-www-form-urlencoded"
,整个响应看起来像下面这个例子,我没有看到任何表单参数:
{:ssl-client-cert nil, :remote-addr "127.0.0.1", :scheme :http, :request-method :post, :query-string nil, :content-type "application/x-www-form- urlencoded", :uri "/api/tasks/remove", :server-name "localhost", :headers {"user-agent" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11", "origin" "http://localhost:8099", "accept-charset" "ISO-8859-1,utf-8;q=0.7,*;q=0.3 ", "接受" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "host" "localhost:8099", "referer" "http:// localhost:8099/form.html", "content-type" "application/x-www-form-urlencoded", "cache-control" "max-age=0", "accept-encoding" "gzip,deflate,sdch", "content-length" "23", "accept-language" "en-US,en;q=0.8", "connection" " keep-alive"}, :content-length 23, :server-port 8099, :character-encoding nil, :body #}
我的问题分为两部分:
- 提交表单时 ring 或 jetty 到底在做什么?
- 如果我正在尝试编写自己的
handler
代码来处理表单数据,那么我如何访问表单查询参数的简化代码框架是什么?
我已经将这个函数的“魔力”隔离在params.clj
:
(defn- assoc-form-params
"Parse and assoc parameters from the request body with the request."
[request encoding]
(merge-with merge request
(if-let [body (and (urlencoded-form? request) (:body request))]
(let [params (parse-params (slurp body :encoding encoding) encoding)]
{:form-params params, :params params})
{:form-params {}, :params {}})))
特别是这一行:
(parse-params (slurp body :encoding encoding) encoding)
但我不确定它在做什么。