2

大约 10 多年前,我在适度涉足 clojure 之后又回到了它,所以我可能在这里做一些愚蠢的事情。

我正在尝试使用compojurering服务器编写一个简单的 API,现在我已经将我的问题隔离为几行。我有一条路线和一个处理程序,并且我已经按照文档wrap-json-body中的建议包装了我的处理程序ring-json

handler.clj的是这样的:

(defroutes app-routes 
  (PUT "/item/:id" {{id :id} :params body :body} (str id ", " body))
  (route/not-found "Not Found"))

(def app
  (-> app-routes
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))

这应该很简单,我可以将 clojure 数据返回为 json OK。问题是当我尝试读取PUT请求正文 json 时。

$ curl -XPUT -H "Content-type: application/json" -d '{ "id": 32, "name": "pad" }' 'localhost:3001/item/5'
5, {"id" 32, "name" "pad"}

我希望body被填充{:id 32 :name "pad"}

这是整个请求对象:

; (PUT "/item/:id" body (str id body))
$ curl -XPUT -H "Content-type: application/json" -d '{ "id": 32, "name": "pad" }'

{:ssl-client-cert nil, :protocol "HTTP/1.1", :remote-addr "0:0:0:0:0:0:0:1", :params {:id "5"}, :route-params {:id "5"}, :headers {"user-agent" "curl/7.58.0", "host" "localhost:3001", "accept" "*/*", "content-length" "27", "content-type" "application/json"}, :server-port 3001, :content-length 27, :compojure/route [:put "/item/:id"], :content-type "application/json", :character-encoding "UTF-8", :uri "/item/5", :server-name "localhost", :query-string nil, :body {"id" 32, "name" "pad"}, :scheme :http, :request-method :put}

我已经对其进行了调整并将其更改为一些内容,但似乎:body无法填充关键字编辑的 clojure 数据。

请问我做错了什么?

ps:如果你想看这个问题的工作示例,我已经将它上传到github

4

1 回答 1

4

使用wrap-json-bodykeywords?中的参数:

(middleware/wrap-json-body app-routes {:keywords? true})

或者,从 ring-clojure 版本 0.5.1 开始,您可以指定自定义key-fn来转换地图的键:

(middleware/wrap-json-body app-routes {:key-fn keyword})
于 2021-05-02T08:46:27.177 回答