如何在 clojurescript 中获取查询参数?

How to get query parameters in clojurescript?

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

(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

我实际上想要实现的是从 friend 解析登录失败,如果失败会将我重定向到

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

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

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

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

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

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

(require '[cemerick.url :as url])
(:query (url/url (-> js/window .-location .-href)))

来自docs

如果 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\"}"