Compojure没有获得请求正文

时间:2016-02-19 02:41:59

标签: clojure compojure

我有一个使用Compojure的应用程序与这种端点

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_margin="20dp"
        android:layout_height="100dp">
        <View
            android:id="@+id/button_view"
            android:layout_width="match_parent"
        android:layout_height="match_parent"
            android:background="#0f0"
            android:transitionName="MyTransition"/>
    </LinearLayout>
</LinearLayout>

当我尝试这个卷曲请求时

(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 -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",但我宁愿提交json。我知道我可能会使用compojure-api,但我很好奇为什么会这样做。

2 个答案:

答案 0 :(得分:3)

您需要使用ring-json中间件,尤其是wrap-json-body来解析json参数:

  

wrap-json-body中间件将使用JSON内容类型的任何请求的主体解析为Clojure数据结构,并将其分配给:body key。

     

这是处理JSON请求的首选方法。

答案 1 :(得分:0)

尝试在处理程序中添加wrap-json-params中间件。