我正在努力从投入中返回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)))
Run Code Online (Sandbox Code Playgroud)
我只是想以JSON的形式返回传递给put请求的任何内容,直到我理解发生了什么为止.
但是如果我发出一个put请求,我得到以下响应:
HTTP/1.1 201已创建
日期:太阳,2014年5月18日15:35:32 GMT
Content-Type:text/plain
内容长度:0
服务器:码头(7.6.8.v20121106)
我的GET请求返回JSON,所以我不明白为什么PUT请求不是/
这是因为成功的PUT请求不返回http 200状态代码(至少根据解放器),它返回一个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.
Run Code Online (Sandbox Code Playgroud)
由于您在:handle-created上声明none,因此它默认为带有text/plain content-type的空字符串.
编辑:
为了了解更多信息,您必须查看决策图.在那里,你可以看到在处理之后put!它会进入决策处理new?,如果是真的则转到handle-createdif,respond-with-entity?等等.
| 归档时间: |
|
| 查看次数: |
787 次 |
| 最近记录: |