如何在`figwheel` dev服务器中进行代理?

时间:2017-05-17 09:29:49

标签: clojurescript figwheel

grunt / webpack / express中,我可以将其他域/主机名中的某些API代理到服务于html页面的当前服务器,并解决CORS问题。< / p>

我发现figwheel使用ring启动http服务器,然后我想我可以使用https://github.com/tailrecursion/ring-proxyfigwheel服务器添加代理路径。但我不知道如何在figwheel项目之外做到这一点。

谢谢!

1 个答案:

答案 0 :(得分:0)

我使用Luminus框架并将其添加到Luminus框架middleware.clj

(defn create-proxy [handler fns]
  ;; TODO check whether cookies are sent
  (let [identifier-fn (get fns :identifier-fn identity)
        host-fn (get fns :host-fn {})
        path-fn (get fns :path-fn identity)]
    (fn [request]
      (let [request-key (identifier-fn request)
            host (host-fn request-key)
            stripped-headers (dissoc (:headers request) "content-length" "host")
            path (path-fn (:uri request))]
        (if host
          (->
           {:url              (build-url host (path-fn (:uri request)) (:query-string request))
            :method           (:request-method request)
            :body             (if-let [len (get-in request [:headers "content-length"])]
                                (slurp-binary
                                 (:body request)
                                 (Integer/parseInt len)))
            :headers          stripped-headers
            :follow-redirects true
            :throw-exceptions false
            :as               :stream
            :insecure?        true
            }
           clj-http.client/request
           (update-in [:headers] dissoc "Transfer-Encoding")
           )
          (handler request))
        ))))


(defn wrap-proxy [handler]
  (-> handler
      (create-proxy
       {:identifier-fn :uri
        :host-fn (proxy-map-2-host-fn proxy-map)
        :path-fn (fn [^String uri]
                   (subs uri (inc (.indexOf (rest uri) \/))))})))

并将app-routes中的handler.clj更改为:

(def app-routes
 (routes
    (-> #'home-routes
        (wrap-routes middleware/wrap-csrf)
        (wrap-routes middleware/wrap-formats))
    (middleware/wrap-proxy
     (route/not-found
      (:body
       (error-page {:status 404
                    :title "page not found"}))))))

proxy-map可能是这样的:

(def proxy-map "proxy map"
  {"/www" "https://www.example.com"
   "/test" "http://test.example.com"
   }
  )

它有效。但是,在使用此框架时,我不再需要cider-jack-in-clojurescript,每当我保存.cljs文件时都会重新加载网页。因此,只需将任何跨站点路由添加到proxy-map并使用相应的密钥进行访问。

例如,使用(GET "/www/some-path'")就像请求(GET "https://www.example.com")一样有效。

顺便说一句,这些代码中的大部分都是从https://github.com/tailrecursion/ring-proxy和其他类似的回购邮件中窃取的。