我正在学习使用Closure / Compojure,我在构建一个小型网络应用程序时遇到了问题。
我在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 / patient的那个,我希望用以下代码获得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输出,我正在执行患者处理程序的代码,你们知道我是否遗漏了什么?
提前致谢!抱歉我的英文奇怪!
答案 0 :(得分:2)
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))