10

我正在使用秘书和试剂。这是我的代码:

(def view (atom nil))

(defn layout [view]
  [:div @view])

(reagent/render-component [layout view] (.getElementById js/document "message"))

(secretary/set-config! :prefix "")

(secretary/defroute home-path "/" [query-params]
  (timbre/info "Path : /, query params : " query-params)
  (let [warning (:warning query-params)
        success (:success query-params)
        login-failed (:login_failed query-params)]
    (when warning
      (timbre/info "Warning found : " warning)
      (reset! view [:h4 [:span.label.label-warning warning]]))
    (when success
      (timbre/info "Success found : " success)
      (reset! view [:h4 [:span.label.label-info success]]))
    (when login-failed
      (timbre/info "Login failed")
      (reset! view [:h4 [:span.label.label-warning "Login Failed."]]))))

(let [h (History.)]
 (goog.events/listen h EventType.NAVIGATE #(secretary/dispatch! (.-token %)))
 (doto h
  (.setEnabled true)))

忽略 :prefix 值(我尝试了“”、“#”并且根本没有设置 :prefix)此代码仅适用于以下路由:

http://localhost:8080/login#/?success=SuccessMessage

但它不适用于以下路线:

http://localhost:8080/login?success=SuccessMessage

我实际上想要实现的是解析来自朋友的登录失败,如果失败将我重定向到

http://localhost:8080/login?&login_failed=Y&username=someUser

并向用户显示登录失败消息。我不需要为此使用秘书,任何可以解析查询参数的东西对我来说都可以。

困难的方法是解析我可以得到的查询字符串:

(-> js/window .-location .-search)

我相信这在某些图书馆已经做得很好了。

4

2 回答 2

15

我找到了。使用https://github.com/cemerick/url(适用于 clojure 和 clojurescript),可以这样做:

(require '[cemerick.url :as url])
(:query (url/url (-> js/window .-location .-href)))
于 2015-09-15T06:21:08.667 回答
1

文档

如果 URI 包含查询字符串,它将自动提取到 :query-params 用于字符串路由匹配器和最后一个元素用于正则表达式匹配器。

(defroute "/users/:id" [id query-params]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

(defroute #"/users/(\d+)" [id {:keys [query-params]}]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

;; In both instances...
(secretary/dispatch! "/users/10?action=delete")
;; ... will log
;; User: 10
;; "{:action \"delete\"}"
于 2019-09-30T13:05:41.697 回答