【问题标题】:ring response downloads index.html instead of rendering it响铃响应下载 index.html 而不是渲染它
【发布时间】:2016-09-25 11:28:37
【问题描述】:

我有一个位于resources/public/index.htmlindex.html 并定义了以下路由(应用程序被拆分得更多,只是使代码简洁):

(ns example.example
  (:require [compojure.route :as route]))

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

(defroutes application-routes
           routes
           (route/resources "/")
           (route/not-found (resource-response "index.html" {:root "public"} "text/html")))


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

但是,当我转到 localhost:8090/ 时,它会下载 html 文件而不是渲染它。

如果我转到localhost:8090/index.html,它会正确呈现文件,所以我认为我的路由不正确,但在查看示例后我不太清楚为什么。

【问题讨论】:

标签: clojure compojure ring


【解决方案1】:

这与question 完全相同。

您需要创建一个中间件来更新您的请求:

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

然后包装你的路线:

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

填写handler.clj

【讨论】:

    【解决方案2】:

    使用这个:

    (:require [clojure.java.io :as io]
              [ring.middleware.resource :as resource])
    
    (defroutes routes
    
         (GET "/" []
                 (io/resource "index.html")))
    

    还可以使用中间件进行资源包装

    (resource/wrap-resource "/public") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 2021-10-12
      • 2015-10-22
      相关资源
      最近更新 更多