0
votes

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 "/"))))
1
Take a look at stackoverflow.com/questions/35828884/… - 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
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
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
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

1 Answers

1
votes

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.