json - Clojure 包装-json-响应返回 404

标签 json clojure compojure

我正在学习使用 Closure/Compojure,但在构建小型 Web 应用程序时遇到问题。

我在 mywebapp/routes.clj 上定义了以下路由

(defroutes app-routes
  (GET "/" [] (index-page))
  (GET "/about" [] (about-page))
  (GET "/bluebutton" [] (bluebutton-page))
  (GET "/bluebutton/patient" [] (patient-handler))
  (route/resources "/")
  (route/not-found "No page"))

还有一个不工作的/bluebutton/patent,我希望得到一个包含以下代码的 JSON 响应:

(use '[ring.middleware.json :only [wrap-json-response]]
     '[ring.util.response :only [response]])

(defn patient-handler []
  (println "patient-handler")
  (wrap-json-response (response {:body {:foo "bar"}})))

出于某种原因,我在浏览器上收到 404 响应,但我正在检查 REPL 输出,表明我正在执行患者处理程序的代码,你们知道我是否遗漏了某些内容吗?

提前致谢!抱歉我的英语很奇怪!

最佳答案

wrap-json-response 采用一个函数作为参数并返回一个新函数,该函数在调用时将进行 json 包装。像这样:

(defn patient-handler []
  (println "patient-handler")
  (middleware/wrap-json-response (fn [_] (response {:body {:foo "bar"}}))))

尽管更正常的应用程序会将其拆分为它自己的函数(或整个命名空间):

(ns hello-web.handler
  (:require [compojure.core :refer :all]
            [compojure.handler :as handler]
            [ring.middleware.json :as middleware]
            [compojure.route :as route]
            [ring.util.response :refer [response]]))

(defroutes app-routes
  (GET "/" [] "Hello World")
  (route/resources "/")
  (GET "/bluebutton/patient" [] (patient-handler))
  (route/not-found "Not Found"))

(def app
  (handler/site app-routes))

(defn create-json-response [request]
  (response {:body {:foo "bar"}}))

(defn patient-handler []
  (println "patient-handler")
  (middleware/wrap-json-response create-json-response))

关于json - Clojure 包装-json-响应返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25021461/

相关文章:

json - SwiftyJSON - 无法从 JSON 字符串获取 transactionId

json - 如何在 D 中使用 JSON 数据发出 http POST 请求

clojure - 使用 leiningen 构建 Debian 和 Redhat 软件包

clojure - 在 Clojure 中比较字符串的正确方法是什么?

clojure - 如何在 Compojure/Ring 中区分 html 与 xhr/xml/json 请求?

php - json 响应中的函数名称 - 不起作用

javascript - 如何在 Javascript 中动态选择 JSON 对象分组的属性

clojure - 根据字符串类名创建一条记录

google-app-engine - lein appengine-prepare 失败

Clojure 中的宏、评估和引用