在Compojure中默认为/默认提供index.html

Kev*_*rke 32 clojure compojure

我有一个静态文件index.html,我想在有人请求时提供服务/.通常,Web服务器默认执行此操作,但Compojure不这样做.index.html当有人请求时,我如何让Compojure服务/

这是我用于静态目录的代码:

; match anything in the static dir at resources/public
(route/resources "/")
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 39

另一种方法是在附加路径中创建重定向或直接响应.像这样:

(ns compj-test.core
  (:use [compojure.core])
  (:require [compojure.route :as route]
            [ring.util.response :as resp]))

(defroutes main-routes
  (GET "/" [] (resp/file-response "index.html" {:root "public"}))
  (GET "/a" [] (resp/resource-response "index.html" {:root "public"}))
  (route/resources "/")
  (route/not-found "Page not found"))
Run Code Online (Sandbox Code Playgroud)

"/"路由返回"index.html"的文件响应,该响应存在于公用文件夹中."/ a"路由通过'内联'文件index.html直接响应.

有关响铃的更多信息:https://github.com/mmcgrana/ring/wiki/Creating-responses

编辑:删除不必要的[ring.adapter.jetty]导入.

  • 你好.(获取"/"[](resp/resource-response"index.html"{:root"public"}))对我来说非常适合. (6认同)

小智 26

(ns compj-test.core
  (:use [compojure.core])
  (:require
        [ring.util.response :as resp]))

(defroutes main-routes
  (GET "/" [] (resp/redirect "/index.html")))
Run Code Online (Sandbox Code Playgroud)

您要求的是从/到/index.html的重定向.它就像(resp/redirect target)一样简单.无需过度复杂化.

  • 这是最直接和合乎逻辑的回应,谢谢! (2认同)

ama*_*loy 24

这将是一个非常简单的Ring中间件:

(defn wrap-dir-index [handler]
  (fn [req]
    (handler
     (update-in req [:uri]
                #(if (= "/" %) "/index.html" %)))))
Run Code Online (Sandbox Code Playgroud)

只需使用此函数包装您的路由,并在其余代码看到之前将/请求转换为请求/index.html.

(def app (-> (routes (your-dynamic-routes)
                     (resources "/"))
             (...other wrappers...)
             (wrap-dir-index)))
Run Code Online (Sandbox Code Playgroud)

  • 我想我的观点是:Compojure没有这样做,因为很容易用Ring做.您的Clojure Web堆栈不是一个包罗万象的平台,而是一系列可插拔和专用的工具.使用专为其设计的工具解决问题X. (3认同)

Bin*_*ati 19

这很好用.无需编写环形中间件.

(:require [clojure.java.io :as io])

(defroutes app-routes 
(GET "/" [] (io/resource "public/index.html")))
Run Code Online (Sandbox Code Playgroud)


fas*_*fgs 10

在这里查看了很多答案后,我使用以下代码:

(ns app.routes
  (:require [compojure.core :refer [defroutes GET]]
            [ring.util.response :as resp]))

(defroutes appRoutes
  ;; ...
  ;; your routes
  ;; ...
  (GET "/" []
       (resp/content-type (resp/resource-response "index.html" {:root "public"}) "text/html"))))
Run Code Online (Sandbox Code Playgroud)
  • 没有重定向;
  • 不需要另一个中间件;
  • index.html保留在正确的文件夹中(resources/public/index.html);
  • 它适用于其他中间件(当使用某些环默认中间件时,很多答案都会中断);
  • 它提供内容类型,因此它适用于包装内容类型的中间件.

检查响铃默认值.它具有您应该在项目中使用的最佳实践中间件.