如何使用 Clojure Liberator 返回 json 数据?此代码不起作用:
(defresource poster []
:allowed-methods [:post :options]
:available-media-types ["application/json"]
:post! (fn [ctx] (println "posting..."))
:handle-created (fn [ctx] {:created "ok"}))
是否应该在发布后调用handle-created?
最佳答案
与 :post!
键关联的函数不是处理函数。 Liberator 文档将其称为操作函数。
Action functions The keys :post!, :put! and :delete! provide points that are suited well to enact side effects. While they are evaluated like decision functions, the boolean value has no effect and the next decision step is constant. The context update works exactly like for decision functions.
因此您无法直接从与 :post!
关联的函数生成 http 响应。
与 :post!
键关联的函数可以返回一些内容,并且该内容将被合并到上下文中。
The context update works exactly like for decision functions.
然后处理函数可以稍后从上下文中提取该内容并使用它来形成 http 响应。与这些键关联的任何一个处理函数都可能随后执行::handle-ok
、:handle-created
、:handle-no-内容
,:handle-see-other
,:handle-multiple-representations
这个decision graph确定将执行哪个处理程序。
最好只使用指向新创建的资源的位置 header 进行响应,而不使用正文,但这里是一个使用 JSON 正文和 201 状态创建响应的示例。
(POST "/foo" [] (resource :allowed-methods [:post]
:available-media-types ["application/json"]
:handle-created {:created "ok"}))
尝试一下:
curl -X POST "localhost/foo"
{"created":"ok"}
您可以在 project.clj 中看到 Liberator 使用哪个 JSON 库文件。如果你想自己生成 JSON 字符串,你可以这样做:
:handle-created (fn [ctx] (liberator.representation/ring-response
{:status 201 :body "{created:\"ok\"}"}))
提到here
关于clojure - 如何从post返回json数据! Clojure 解放者中的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107448/