Ring和Compojure - 使用content-type为application/json的POST请求无法工作

3

如何以application/json的content-type发送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 命令时记录的参数:
````

以下是我运行 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}

请查看 :form-params 键。 - Jonah Benton
我添加了错误的输出。我刚刚进行了编辑 :) - bpereira
1个回答

3
您可以“ slurp ”输入流(将其读入字符串)并解析其JSON。类似于这样:

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

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

但是你应该使用Ring中间件来自动完成这个任务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接