【问题标题】:Match and GET request in Compojure for react-router browserHistory在 Compojure 中为 react-router browserHistory 匹配和获取请求
【发布时间】:2016-03-13 09:15:38
【问题描述】:

我想为任何 GET 请求路径提供以下路由,以便我可以使用前端路由库 (react-router)。

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

这是我尝试过的:

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

它们都给出相同的错误:

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

Unexpected token 是index.html 中的第一个&lt;

所以我的问题是如何调整我的 Compojure/Ring/Immutant 堆栈以与 react-router 配合使用?

更新: 我还尝试了以下中间件,将所有请求更改为根但没有运气:

(defn wrap-dir-index [handler]
  (fn [req]
    (handler
     (assoc req :uri "/"))))

【问题讨论】:

  • 看看stackoverflow.com/questions/35828884/… - 当您使用该代码时,来自resources/public 的所有文件都将由服务器提供,所有以/ 结尾的路径都将提供/index.html
  • 我希望每个 GET 都服务于 /index.html,而不仅仅是以 / 结尾的那个。我已经用其他替代方法更新了我的问题,但我仍然无法让事情按我的意愿工作。
  • 其他资源如 javascript 和 css 呢?它们都嵌入到您的 index.html 中了吗?或者,如果找不到特定资源,您可能想提供 resources/public 中的任何内容并回退到提供 index.html 的内容?
  • 是的,这正是我想要做的:) 但是,当尝试使用建议帖子中的代码时,它不起作用。

标签: clojure compojure


【解决方案1】:

您可以按照Ring wiki page 中的说明使用wrap-resource,并结合一条包罗万象的路线:

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

我认为最好从所有其他 URL 重定向到“/”,这样您的应用程序始终使用相同的基地址工作。

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 2019-06-17
    • 2017-10-04
    • 2016-04-28
    • 2017-09-13
    • 1970-01-01
    • 2017-09-25
    • 2013-03-16
    相关资源
    最近更新 更多