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]导入.
小智 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)一样简单.无需过度复杂化.
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)
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)
检查响铃默认值.它具有您应该在项目中使用的最佳实践中间件.
| 归档时间: |
|
| 查看次数: |
10522 次 |
| 最近记录: |