【问题标题】:Ring wrap-json-body is not converting json data to keyword map, but to a string mapRing wrap-json-body 不是将 json 数据转换为关键字映射,而是转换为字符串映射
【发布时间】:2021-07-25 00:02:23
【问题描述】:

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

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

我的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

【问题讨论】:

    标签: clojure compojure clojure-ring


    【解决方案1】:

    使用wrap-json-body中的keywords?参数:

    (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-10
    • 2015-07-06
    • 2013-01-18
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多