clojure - Compojure 没有得到请求正文

标签 clojure compojure

我有一个使用 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/

相关文章:

java - Scala/Clojure 互操作可以在 PC 上运行,但在另一台 PC 上失败并出现 java.lang.ExceptionInInitializerError

clojure - 将项目 -> 类别向量的 clojure 映射解析为分类列表

web-applications - friend 的 bcrypt-credential-fn 的正确用法是什么?

authentication - 在 Clojure Web 应用程序中使用 JSON 请求正文而不是请求参数进行好友身份验证

session - 复合/环 : Why doesn't a session with cookie-store survive a server restart?

clojure - 哪些语言特性可以通过库添加到 Clojure 中?

Clojure:文档

clojure - 将数据传递给黑色 View - Clojure

maven - leiningen项目中使用maven的 "LATEST"关键字

macros - 编写宏时获取原始符号名称