【问题标题】:Serving index.html file from compojure从 compojure 提供 index.html 文件
【发布时间】:2016-06-20 03:01:56
【问题描述】:

我是 clojure 和 compojure 的新手,我尝试将 compojure 与 ring 一起创建一个基本的 Web 应用程序。

这是我的 handler.clj

(ns gitrepos.handler
  (:require [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.util.response :as resp]
            [ring.middleware.defaults :refer [wrap-defaults site-defaults]]))

(defroutes app-routes
  (GET "/" [] (resp/file-response "index.html" {:root "public"}))
  (route/not-found "Not Found"))

(def app
  (wrap-defaults app-routes site-defaults))

我在 /resources/public 下有这个 index.html 文件,但应用程序没有呈现这个 html 文件。而是得到未找到

我已经搜索了很多,即使这个Serve index.html at / by default in Compojure似乎也无法解决问题。

不确定我在这里缺少什么。

【问题讨论】:

    标签: clojure compojure


    【解决方案1】:

    也许您想尝试使用一些模板库,例如Selmer。所以你可以这样做:

    (defroutes myapp
      (GET "/hello/" []
        (render-string (read-template "templates/hello.html"))))
    

    或者传递一些值:

    (defroutes myapp
      (GET "/hello/" [name]
        (render-string (read-template "templates/hello.html") {name: "Jhon"})))
    

    正如@piotrek-Bzdyl 所说:

    (GET  "/" [] (resource-response "index.html" {:root "public"}))
    

    【讨论】:

    • 这似乎是更好的选择,尝试了clostache,它奏效了,谢谢。
    • 不错!是的,clostache 也是一种选择
    【解决方案2】:

    纳温

    这是我自己的一个似乎有效的 sn-p。和你的相比,你在defroutes没有资源路径:

    (defroutes default-routes
      (route/resources "public")
      (route/not-found
       "<h1>Resource you are looking for is not found</h1>"))
    
    (defroutes app
      (wrap-defaults in-site-routes site-defaults)
      (wrap-defaults test-site-routes site-defaults)
      (wrap-restful-format api-routes)
      (wrap-defaults default-routes site-defaults))
    

    【讨论】:

      【解决方案3】:

      由于site-defaults,您无需指定使用file-responseresoures/public 提供文件的路由,此目录将提供服务。您唯一缺少的部分是将/ 路径映射到/index.html,这可以使用您在另一个问题中提到的代码来完成。所以解决方案是:

      (defn wrap-dir-index [handler]
        (fn [req]
          (handler
            (update
              req
              :uri
              #(if (= "/" %) "/index.html" %)))))
      
      (defroutes app-routes
        (route/not-found "Not Found"))
      
      (def app
        (-> app-routes
          (wrap-defaults site-defaults)
          (wrap-dir-index)
      

      附带说明,您应该更喜欢使用ring.util.response/resource-response,因为它从类路径提供文件,并且在您将应用程序打包成 jar 文件时也可以使用。 file-response 使用文件系统来定位文件,并且不能在 jar 文件中工作。

      【讨论】:

      • 投反对票的人能否解释我的回答有什么问题?如果我知道错误的原因,我会非常乐意修复或删除它。
      猜你喜欢
      • 2014-10-10
      • 2012-02-11
      • 2011-12-05
      • 2013-05-25
      • 2020-08-08
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多