index.html
誰かが要求したときに提供したいという静的ファイルがあります/
。通常、Web サーバーはデフォルトでこれを行いますが、Compojure は行いません。index.html
誰かが要求したときにCompojure を提供するにはどうすればよい/
ですか?
静的ディレクトリに使用しているコードは次のとおりです。
; match anything in the static dir at resources/public
(route/resources "/")
別の方法として、追加のルートでリダイレクトまたはダイレクト レスポンスを作成することもできます。そのようです:
(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"))
"/" ルートは、パブリック フォルダーに存在する "index.html" のファイル レスポンスを返します。「/a」ルートは、ファイル index.html を「インライン化」することによって直接応答します。
リング応答の詳細: https://github.com/mmcgrana/ring/wiki/Creating-responses
編集:不要な[ring.adapter.jetty]
インポートを削除しました。
(ns compj-test.core
(:use [compojure.core])
(:require
[ring.util.response :as resp]))
(defroutes main-routes
(GET "/" [] (resp/redirect "/index.html")))
あなたが求めているのは、/ から /index.html へのリダイレクトです。(resp/redirect target) と同じくらい簡単です。物事を過度に複雑にする必要はありません。
これは非常に単純な Ring ミドルウェアになります。
(defn wrap-dir-index [handler]
(fn [req]
(handler
(update-in req [:uri]
#(if (= "/" %) "/index.html" %)))))
この関数でルートをラップするだけで、コードの残りの部分がそれらを見る前に/
get のリクエストがリクエストに変換されます。/index.html
(def app (-> (routes (your-dynamic-routes)
(resources "/"))
(...other wrappers...)
(wrap-dir-index)))
これはうまくいきます。リングミドルウェアを書く必要はありません。
(:require [clojure.java.io :as io])
(defroutes app-routes
(GET "/" [] (io/resource "public/index.html")))
ここで多くの回答を見た後、次のコードを使用しています。
(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"))))
ring-defaults を確認します。プロジェクトで使用する必要があるベスト プラクティスのミドルウェアが含まれています。
最近、Clojure/Compojure アプリが Jetty または Tomcat で .war として実行されている場合、@amaloy の回答が機能しないことがわかりました。この場合:path-info
、更新する必要があります。また、このバージョンは「ルート」ルートだけでなく、あらゆるルートを処理できると思います。
(defn- wrap-dir-index [handler]
(fn [request]
(handler
(let [k (if (contains? request :path-info) :path-info :uri) v (get request k)]
(if (re-find #"/$" v)
(assoc request k (format "%sindex.html" v))
request)))))
参照: https://groups.google.com/forum/#!msg/compojure/yzvpQVeQS3w/RNFkFJaAaYIJ
更新:例を機能するバージョンに置き換えました。
他のコードが機能しない場合は、このコードを試してください。
(GET "/about/" [] (ring.util.response/content-type
(ring.util.response/resource-response "about/index.html" {:root "public"}) "text/html"))
ビニータ、私が経験してきた落とし穴です。Compojureルートを定義する順序の重要性に関するドキュメントが見つかりませんでしたが、これが機能しないことがわかりました
(GET "/*" [] r/static)
(GET "/" [] (clojure.java.io/resource "public/index.html"))
これは機能しますが
(GET "/" [] (clojure.java.io/resource "public/index.html"))
(GET "/*" [] r/static)
明らかに *
空の文字列にも一致しますが、順序はまったく問題ではないと思いました。