【问题标题】:clojure liberator - returning json from a put requestclojure liberator - 从 put 请求中返回 json
【发布时间】:2014-05-18 15:45:31
【问题描述】:

我正在努力从 put 中返回 JSON!请求:

我的代码如下所示:

(defn body-as-string [ctx]
  (if-let [body (get-in ctx [:request :body])]
    (condp instance? body
      java.lang.String body
      (slurp (io/reader body)))))

(defn orbit-world [dimensions ctx]
  (let [in (json/parse-string (body-as-string ctx))]
    (json/generate-string in)))

(defn init-world [params]
  (let [dimensions (Integer/parseInt params)
     world (vec (repeat dimensions (vec (take dimensions (repeatedly #(rand-int 2))))))]
    (json/generate-string world)))

(defresource world [dimensions]
  :allowed-methods [:get :put]
  :available-media-types ["application/json"]
  :available-charsets ["utf-8"]
  :handle-ok (fn [_] (init-world dimensions))
  :put! (fn [ctx] (orbit-world dimensions ctx)))

我只想将传递给 put 请求的任何内容作为 JSON 返回,直到我了解发生了什么。

但如果我提出 put 请求,我会得到以下响应:

HTTP/1.1 201 创建

日期:2014 年 5 月 18 日星期日 15:35:32 GMT

内容类型:文本/纯文本

内容长度:0

服务器:码头(7.6.8.v20121106)

我的 GET 请求返回 JSON,所以我不明白为什么 PUT 请求不是/

【问题讨论】:

    标签: clojure liberator


    【解决方案1】:

    这是因为成功的 PUT 请求不会返回 http 200 状态码(至少根据 liberator),它返回的是 http 201 状态码,正如您从响应中看到的那样。 Liberator 在不同的处理程序中处理每个 http 状态代码。为了达到你想要的,你必须做到:

    (defresource world [dimensions]
      :allowed-methods [:get :put]
      :available-media-types ["application/json"]
      :available-charsets ["utf-8"]
      :handle-ok (fn [_] (init-world dimensions))
      :put! (fn [ctx] (orbit-world dimensions ctx))
      :handle-created (fn [_] (init-world dimensions))) ; Basically just a handler like any other.
    

    由于您在 :handle-created 上声明 none,它默认为具有 text/plain 内容类型的空字符串。

    编辑:

    要了解更多,您必须查看decision graph。在那里,您可以看到处理完put! 后,它转到决策处理new?,如果为真,则转到handle-created,如果为假,则转到respond-with-entity?,依此类推。

    【讨论】:

    • 添加 Liberator wrap-trace 中间件真的很有帮助。然后,您将在响应中获得 X-Liberator 标头,这些标头显示解放者在各个决策点的状态。它还向您显示使用了哪个处理程序。在这种情况下,它将显示正在使用默认的句柄创建。
    猜你喜欢
    • 2013-07-19
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2017-09-21
    • 1970-01-01
    相关资源
    最近更新 更多