Ring 和 Compojure - POST 内容类型 application/json 的请求不起作用

Ring and Compojure - POST Requests with content-type application/json does not work

发送内容类型为 application/json 的 POST 请求的正确方法是什么?

当我向我的应用程序发送请求时,我无法检索参数。

curl -X POST http://localhost:3000/agents --data '{"name":"verma"}' --header "Content-type:application/json"

我正在使用:

[org.clojure/clojure "1.8.0"]
[compojure "1.5.1"]
[ring/ring-defaults "0.2.1"]]

我的 handler.cljs 是:

▾|    1 (ns sof.rest.handler
 |    2   (:require [compojure.core :refer :all]
 |    3             [compojure.route :as route]
 |    4             [clojure.data.json :as json]
 |    8             [ring.middleware.defaults :refer [wrap-defaults api-defaults]]))
 |    9
 |   10 (defn json-response [data & [status]]
 |   11   {:status (or status 200)
 |   12    :headers {"Content-Type" "application/json"}
 |   13    :body (json/write-str data)})
 |   14
 |   15 (defroutes app-routes
 |~  16   (POST "/agents" params (println params))
 |   21
~|   22 (def app
~|   23   (wrap-defaults app-routes api-defaults))

这些是我 运行 CURL 命令时记录的参数:

{:ssl-client-cert nil, :remote-addr 0:0:0:0:0:0:0:1, :params {}, :route- 
params {}, :headers {accept */*, user-agent curl/7.54.0, content-type 
application/json, content-length 16, host localhost:3000}, :server-port 
3000, :content-length 16, :form-params {}, :compojure/route [:post 
/agents], :query-params {}, :content-type application/json, :character- 
encoding nil, :uri /agents, :server-name localhost, :query-string nil, 
:body #object[org.eclipse.jetty.server.HttpInput 0x70504fbe 
org.eclipse.jetty.server.HttpInput@70504fbe], :scheme :http, :request- 
method :post}

您可以 slurp :body 输入流(将其读入字符串)并解析其 JSON。像这样:

(POST "/agents" request
  (let [body (json/read-str (slurp (:body request)))]
    (println body)))

但是你应该使用 Ring middleware 来自动执行此操作。