从Compojure提供index.html文件

4

我刚接触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也似乎无法解决该问题。
不确定我错过了什么。
3个回答

1

你好,这里是关于编程的内容。以下是一段我自己写的代码片段,它似乎可以运行。与你的代码相比,你在defroutes中没有资源路径:

Naveen

(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))

1
您不需要指定路由来从 resoures/public 提供文件,使用 file-response 时,此目录下的文件将因为有 site-defaults 而被提供。您唯一缺少的部分是将 / 路径映射到 /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文件中运行。


能否请给我点赞负者解释一下我的回答有什么问题吗?如果我知道哪里错了,我很乐意修改或删除它。 - Piotrek Bzdyl

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,它很有效,谢谢。 - navyad
不错!是的,Clostache也是一个选择。 - Édipo Féderle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接