【问题标题】:Ring and Compojure - POST Requests with content-type application/json does not workRing 和 Compojure - 具有内容类型应用程序/json 的 POST 请求不起作用
【发布时间】:2018-09-03 10:39:19
【问题描述】:

使用内容类型 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}

【问题讨论】:

  • 查看 :form-params 键
  • 我添加了错误的输出。我刚刚编辑了它:)

标签: clojure compojure ring


【解决方案1】:

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

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

但您应该使用Ring middleware 自动执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 2015-10-09
    • 2011-05-19
    • 2018-03-03
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多