Bidi、Ring 和 Lein 的简单 Web 应用程序出现 500 错误

Simple web app of Bidi, Ring and Lein gives a 500 error

我正在学习网络 Clojure。我正在尝试在 Lein 应用程序中实现 Bidi 和 Ring。当我打开网站时,出现 500 错误:

HTTP ERROR: 500

Problem accessing /. Reason:

Response map is nil

Powered by Jetty://

我的文件如下:

./project.clj

(defproject bidi-ring "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
            :url "https://www.eclipse.org/legal/epl-2.0/"}
  :dependencies [[org.clojure/clojure "1.10.0"]
                 [bidi "2.1.6"]
                 [ring/ring-core "1.6.3"]
                 [ring/ring-jetty-adapter "1.6.3"]]
  :repl-options {:init-ns my.app}
  :main my.app)

./src/my/handler.clj

(ns my.handler (:gen-class)
    (:require [bidi.ring :refer (make-handler)]
              [ring.util.response :as res]))
(defn index-handler
  [request]
  (res/response "Homepage"))
(defn article-handler
  [{:keys [route-params]}]
  (res/response (str "You are viewing article: " (:id route-params))))
(def handler
  (make-handler ["/" {"index.html" index-handler
                      ["articles/" :id "/article.html"] article-handler}]))

./src/my/app.clj

(ns my.app (:gen-class)
    (:require [my.handler :refer [handler]]
              [ring.middleware.session :refer [wrap-session]]
              [ring.middleware.flash :refer [wrap-flash]]))
(use 'ring.adapter.jetty)

(defn -main []

  (def app
    (-> handler
        wrap-session
        wrap-flash))

  
  (run-jetty app {:port 3000}))

如何解决?

您的路线有误。查看此 Bidi 演示存储库:

https://github.com/io-tupelo-demo/bidi

tst.demo.core 第 16 行的代码显示了正在发生的事情。在bidi中,路由“/index.html”不包含退化路由“/”:

  (let [routes   ["/" ; common prefix
                  {"index.html"   :index
                   "article.html" :article}]

        routes-2 ["/" ; common prefix
                  {""             :index ; add a default route so "/" and "/index.html" both => `:index` handler
                   "index.html"   :index
                   "article.html" :article}]] 
    (is= (bidi/match-route routes "/index.html") {:handler :index}) ; normal case

    (is= (bidi/match-route routes "/") nil) ; plain "/" route is not available, has no default

    (is= (bidi/match-route routes-2 "/") {:handler :index})) ; Now we get the :index route

当没有路由匹配时,match-route returns nil,然后服务器将其转换为 500 not-found 发送到浏览器。