我有一个使用 Compojure 和这种端点的应用程序
(defroutes routes
(POST "/api/v1/echo" req (str req))
(def http-handler
(reload/wrap-reload (wrap-defaults #'routes api-defaults)))
(defn run-web-server []
(run-jetty http-handler {:port 10555 :join? false}))
当我尝试这个 curl 请求时
curl -X POST -H "Content-Type: application/json" http://localhost:10555/api/v1/echo -d '{"hello": "world"}'
我收到了这个回复
{:ssl-client-cert nil, :remote-addr "0:0:0:0:0:0:0:1", :params {}, :route-params {}, :headers {"accept" "*/*", "user-agent" "curl/7.43.0", "content-type" "application/json", "content-length" "18", "host" "localhost:10555"}, :server-port 10555, :content-length 18, :form-params {}, :query-params {}, :content-type "application/json", :character-encoding nil, :uri "/api/v1/echo", :server-name "localhost", :query-string nil, :body #object[org.eclipse.jetty.server.HttpInput 0x4317e5fa "org.eclipse.jetty.server.HttpInput@4317e5fa"], :scheme :http, :request-method :post}%
我希望在该响应中看到 {"hello", "world"}
某处,但它不在那里。我看到有 :body HttpInput
,但是当我尝试 (prn (-> req :body .read))
时,它输出 123
。因为 (= "{\"hello\",\"world\"}"123) => false
,我有点不知道接下来要尝试什么。
curl -X POST -H "Content-Type: application/x-www-form-urlencoded"http://localhost:10555/api/v1/echo -d "foo=1&bar=2"
确实按预期工作并返回 :params {:foo "1", :bar "2"}
,但我宁愿提交 json。我知道我可能会使用 compojure-api,但我很好奇为什么会这样。
最佳答案
您需要使用 ring-json中间件,特别是 wrap-json-body
来解析 json 参数:
The wrap-json-body middleware will parse the body of any request with a JSON content-type into a Clojure data structure, and assign it to the :body key.
This is the preferred way of handling JSON requests.
关于clojure - Compojure 没有得到请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35496376/