鉴于一些组合路线:
(defroutes app-routes
(GET "/" [] (display-some-html))
(GET "/story" [] (display-more-html))
(GET "/classes" [] (display-other-html))
(POST "/delete" [id] (do (delete-some-id-from-db id)
(magic-redirect-function)))
(route/resources "/")
(route/not-found "Not Found"))
假设我能够从/delete
,/
,/story
发送到/classes
。如何重定向到POST请求源自的页面?
答案 0 :(得分:2)
通常的方法是在会话中使用前一个URL,并在操作后将用户重定向到/渲染相应的视图。如果你正在使用site handler,那么你已经包含了包装会话。
您可以从Ring wiki执行类似于此示例的操作,将其更改为存储请求路径而不是计数。
(defn handler [{session :session}]
(let [count (:count session 0)
session (assoc session :count (inc count))]
(-> (response (str "You accessed this page " count " times."))
(assoc :session session))))
答案 1 :(得分:1)
使用Referrer标头重定向回来
(let [back (get (:headers request) "referer")]
(redirect-to back))
答案 2 :(得分:0)
我的解决方案基于Diego的建议使用lib-noir
。
(ns my-project.handler
(:require (compojure [handler :as handler]
[route :as route]
[core :refer :all])
[ring.util.response :refer [redirect]]
[noir.util.middleware :as middleware]
[noir.session :as session]))
(defroutes app-routes
(GET "/" []
(session/put! :origin "/")
(display-some-html))
(GET "/story" []
(session/put! :origin "/story")
(display-more-html))
(GET "/classes" []
(session/put! :origin "/classes")
(display-other-html))
(POST "/delete" [id]
(delete-some-id-from-db id)
(redirect (session/get! :origin "/"))) ; "/" is an optional default
(route/resources "/")
(route/not-found "Not Found"))
(def app
(->
(handler/site app-routes)
session/wrap-noir-session))
它有效,但我不会称之为优雅。
答案 3 :(得分:0)
deadghost的建议是最好的。在这里,您可以找到使用lib-noir库自动重定向到主页的解决方案。我希望这有助于某人。
(ns hue-web-app.core
(:require [ring.middleware.defaults :refer [wrap-defaults api- defaults site-defaults]]
[ring.util.response :as response] ;;from ring
[compojure.core :refer :all]
[compojure.route :as route]
[noir.util.middleware :as middleware]
[noir.session :as session]] ;;noir for redirect to work
(defroutes hue-app-routes
(GET "/" [] (session/put! :origin "/")
(io/file "resources/testsite.html"))
(GET "/turn-off" [] (turn-group-off 3 user)
(response/redirect (session/get! :origin "/")))
(GET "/turn-on" [] (turn-group-on 3 user)
(response/redirect (session/get! :origin "/"))))
;;STARTING THE SERVER
;;-------------------------------------------------------------- ------------
(defn siteparams
[]
(run-jetty (-> #'hue-app-routes
wrap-reload
wrap-restful-format
wrap-params
session/wrap-noir-session
)
{:port 5003
:join? false}))