4

我的代码:

(defn json-response [data & [status]]
    {:status (or status 200)
     :headers {"Content-Type" "application/json"}
     :body (json/generate-string data)})

(defroutes checkin-app-handler
  (GET "/:code" [code & more] (json-response {"code" code "params" more})))

当我将文件加载到 repl 并运行此命令时,参数似乎为空白:

$ (checkin-app-handler {:server-port 8080 :server-name "127.0.0.1" :remote-addr "127.0.0.1" :uri "/123" :query-string "foo=1&bar=2" :scheme :http :headers {} :request-method :get})
> {:status 200, :headers {"Content-Type" "application/json"}, :body "{\"code\":\"123\",\"params\":{}}"}

我究竟做错了什么?我需要获取查询字符串,但参数映射始终为空..

4

1 回答 1

5

为了将查询字符串解析到 params 映射中,您需要使用 params 中间件:

(ns n
  (:require [ring.middleware.params :as rmp]))

(defroutes checkin-app-routes
  (GET "" [] ...))

(def checkin-app-handler
  (-> #'checkin-app-routes
      rmp/wrap-params
      ; .. other middlewares
      ))

请注意,var ( #'checkin-app-routes) 的使用不是绝对必要的,但它使路由关闭,包裹在中间件中,在您重新定义路由时拾取更改。

IOW 你也可以写

(def checkin-app-handler
  (-> checkin-app-routes
      rmp/wrap-params
      ; .. other middlewares
      ))

但是,在以交互方式重新定义路由时,您也需要重新定义处理程序。

于 2011-07-31T10:35:31.060 回答