【问题标题】:ring-json's wrap-json-response middleware and compojure returns text/plain?ring-json 的 wrap-json-response 中间件和 compojure 返回 text/plain?
【发布时间】:2013-01-31 01:17:19
【问题描述】:

我正在尝试在我的 compojure 应用程序中使用 ring-json 的 wrap-json-response 中间件。我有一个简单的 GET 处理程序,它返回一个地图,例如 {:foo 1},当我点击 URL 时,环以 text/plain 和一个空的响应正文响应。我似乎无法让它响应 JSON 版本的地图。

这是我的处理程序代码:

(ns localshop.handler
  (:use compojure.core)
  (:require [localshop.routes.api.items :as routes-api-items]
            [ring.middleware.json :as middleware]
            [compojure.handler :as handler]
            [compojure.route :as route]))

;; map the route handlers
(defroutes app-routes
  (context "/api/item" [] routes-api-items/routes))

;; define the ring application
(def app
  (-> (handler/api app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-params)
      (middleware/wrap-json-response)))

路由处理函数实际上只是返回一个地图,所以代码很简单,我想我可以省略。如果从组合路由处理程序返回地图是问题所在,那么也许就是这样?

【问题讨论】:

    标签: clojure compojure ring


    【解决方案1】:

    查看this。基本上如果你返回{:body {:my-map "hello"}} 那么它会正常工作。

    【讨论】:

    • 感谢这个回答者,我正在拔头发。这确实应该得到更好的记录。
    • 知道为什么它必须包含在 :body 中吗?
    • 我最好的猜测是因为该方法可以允许除响应正文之外的更多选项,因此它要求您隐式指定{:body {}}
    • 之所以需要这样做是因为 Compojure 和 Ring (隐式)期待 HTTP 响应。他们自动处理简单类型的事实是混乱的根源。请参阅my answera somewhat-related question
    • 你指的是哪个提交哈希?
    【解决方案2】:

    在编写 REST API 时遇到类似的问题。

    当处理程序返回向量时,我得到一个异常,即在 Compojure 的 Renderable 协议中没有实现 PersistentVector 的方法渲染。

    返回map时,headers为空。

    当返回序列时,我得到'text/html'。 所以,我认为在我们的代码中扩展 Renderable 是件好事:来自 clojure 的非常好的礼物。

    但是,作为 hack,为了快速解决问题,我使用下一个中间件:

    (defn wrap-content-json [h]
      (fn [req] (assoc-in (h req) [:headers "Content-Type"] "application/json")))
    

    【讨论】:

      猜你喜欢
      • 2015-11-26
      • 2014-09-21
      • 2018-12-27
      • 1970-01-01
      • 2014-04-21
      • 2020-07-30
      • 2012-10-20
      • 1970-01-01
      • 2014-09-17
      相关资源
      最近更新 更多