3

I have an index.html located in resources/public/index.html and have defined the following routes (application is split up more than this, just making the code concise):

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

However, when I go to localhost:8090/ it downloads the html file instead of rendering it.

If I go to localhost:8090/index.html it renders the file properly so I assumed my routing is incorrect somehow but after looking at examples I am not too sure why.

Chris Edwards
  • 1,518
  • 2
  • 13
  • 23
  • Possible duplicate of [File is downloaded instead of being displayed in the browser](http://stackoverflow.com/questions/35548372/file-is-downloaded-instead-of-being-displayed-in-the-browser) – Piotrek Bzdyl May 27 '16 at 08:27
  • This exact problem is resolved [here](http://stackoverflow.com/questions/7729628/serve-index-html-at-by-default-in-compojure). – kongeor May 27 '16 at 08:29
  • @kongeor using `resp/redirect` still causes the html file to be downlaoded not rendered – Chris Edwards May 27 '16 at 08:41

2 Answers2

2

This is exactly the same issue with this question.

You need to create a middleware to update your request:

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

And then wrap your routes:

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

Complete handler.clj.

Community
  • 1
  • 1
kongeor
  • 712
  • 1
  • 6
  • 14
1

Use this:

(:require [clojure.java.io :as io]
          [ring.middleware.resource :as resource])

(defroutes routes

     (GET "/" []
             (io/resource "index.html")))

Also use middleware for resource wrapping

(resource/wrap-resource "/public") 
Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76