Bra*_*avi 0 http clojure clj-http
我的 Web 客户端(以 编写cljs)连接到后端(以clj),需要进行一些第三方 API 调用。它必须在服务器上完成,然后结果应该以特定的方式转换并发送回客户端。
这是我的网址之一的处理程序
(defn get-orders [req]
(let [{:keys [sig uri]} (api-signature :get-orders)]
(client/get uri
{:async? true}
(fn [response] {:body "something"})
(fn [exception] {:body "error"}))))
Run Code Online (Sandbox Code Playgroud)
{:body "something"}它没有返回,而是返回以下错误:
No implementation of method: :render of protocol: #'compojure.response/Renderable found for class: org.apache.http.impl.nio.client.FutureWrapper
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
当您指定时{:async? true},clj-http.client/get将返回一个未来,它是FutureWrapper您收到的错误消息中的一个。
因此,如果您不需要异步,请不要使用它。这是一个同步环处理程序的示例,它调用第三方 url 并返回返回的响应。
(defn handler [request]
(response {:result (client/get "http://example.com")}))
Run Code Online (Sandbox Code Playgroud)
如果您确实需要异步,请使用环形处理程序的异步版本。
(defn handler [request respond raise]
(client/get "http://example.com"
{:async? true}
(fn [response] (respond {:body "something"}))
(fn [exception] (raise {:body "error"}))))
Run Code Online (Sandbox Code Playgroud)
不要忘记配置网络服务器适配器以使用异步处理程序。例如,对于 Jetty,将:async?flag设置为truelike so
(jetty/run-jetty app {:port 4000 :async? true :join? false})
Run Code Online (Sandbox Code Playgroud)
如果你想同时调用多个第三方url并返回一次给web客户端,使用promise来帮助
(defn handler [request]
(let [result1 (promise)
result2 (promise)]
(client/get "http://example.com/"
{:async? true}
(fn [response] (deliver result1 {:success true :body "something"}))
(fn [exception] (deliver result1 {:success false :body "error"})))
(client/get "http://example.com/"
{:async? true}
(fn [response] (deliver result2 {:success true :body "something"}))
(fn [exception] (deliver result2 {:success false :body "error"})))
(cond
(and (:success @result1)
(:success @result2))
(response {:result1 (:body @result1)
:result2 (:body @result2)})
(not (:success @result1))
(throw (ex-info "fail1" (:body @result1)))
(not (:success @result2))
(throw (ex-info "fail2" (:body @result2))))))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1159 次 |
| 最近记录: |