我正在学习使用 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/