0

I want to serve the following route for any GET request path so that I can use a frontend routing library instead (react-router).

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

This it what I have tried:

(GET "/*" [] (resource-response "index.html" {:root "public"}))
(rfn [] (resource-response "index.html" {:root "public"}))
(GET "/:any{.*}" [] (resource-response "index.html" {:root "public"}))
(GET "/*" [] (ring.util.response/content-type
                     (ring.util.response/resource-response "index.html" {:root "public"}) "text/html"))
(GET "/*" [] (clojure.java.io/resource "public/index.html"))

They all give the same error:

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:5000/index.css".
bundle.js:1 Uncaught SyntaxError: Unexpected token <

And the Unexpected token is the first < in index.html

So my question is how can I adapt my Compojure/Ring/Immutant stack to play nice with react-router?

UPDATE: I have also tried the following midleware, to change all request to the root but with no luck:

(defn wrap-dir-index [handler]
  (fn [req]
    (handler
     (assoc req :uri "/"))))
user3139545
  • 6,882
  • 13
  • 44
  • 87
  • Take a look at http://stackoverflow.com/questions/35828884/serving-index-html-file-from-compojure/35829722#35829722 - when you use that code, all your files from `resources/public` will be served by the server and all paths ending with `/` will serve `/index.html`. – Piotrek Bzdyl Mar 13 '16 at 10:45
  • I want every GET to serve /index.html, not just the one ending with /. I have updated my question with other alternatives but still im not able to get things working as i want. – user3139545 Mar 13 '16 at 14:59
  • What about other resources like javascript and css? Are they all embedded in your index.html? Or maybe you want to serve whatever you have in `resources/public` and fallback to serving `index.html` if a specific resource is not found? – Piotrek Bzdyl Mar 13 '16 at 15:11
  • Yes that is exactly what im trying to do :) However when trying to use the code from the suggested post it did not work. – user3139545 Mar 13 '16 at 15:47

1 Answers1

1

You can use wrap-resource as described on Ring wiki page combined with a catch all route:

(defroutes handler
  (GET "/" []
    (-> (resource-response "index.html" {:root "public"})
        (content-type "text/html))
  (GET "/*" [] (redirect "/")))

(def app
  (-> handler
      (wrap-resource "public")
      (wrap-content-type)
      (wrap-not-modified))

I think it's better to redirect from all other URLs to "/" so your application works always using the same base address.

Piotrek Bzdyl
  • 12,965
  • 1
  • 31
  • 49