Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I communicate with the backend using ClojureScript and Figwheel?

Note: I'm a moderately experienced programmer in general and using clojure but have never done serious web development.

I set up a basic ClojureScript project using Chestnut and walked through the "Hello World" steps just fine. However I would really like to talk to my backend as well. For this purpose I redefined the Reagent code to be

(defn greeting []
  [:input {:type "button"
       :value (:text @app-state)
       :on-click #(http/get {})}])

Which gets a 404 response when clicked. So at least I'm talking to somebody. I can also see evidence of my get-requests in the server.log file. However at this point I'm struggling with a number of conceptual points.

First of all http/get is a function defined in clj-http.client, which wasn't part of the Chestnut setup. It feels like I'm already off track if I have to go hunting for libraries to send something as basic as a get-request.

Secondly the file for the user namespace has the following lines predefined by Chestnut:

(def http-handler
  (wrap-reload #'mypage.server/http-handler))

(defn run []
  (figwheel/start-figwheel!))

I can't see any place where the http-handler is ever used. So I don't understand what that definition even does.

Also the way I understand Figwheel, when I call "run" it'll spin up a new web server which then a) serves the index.html and b) connects to my browser via some TCP port and starts pumping new JavaScript through that connection. This second part is very speculative on my part. If this is actually what happens my next question would be if Figwheel also needs to sit on the other side of that connection or if browsers have some common API that allows code reloading from the outside.

Lastly I can kinda tell that the ring routes and http-handler defined in the mypage/server.clj file (below) are being called somehow, since modifying these changes the error from the get-request, however it's a complete mystery to me how this works. The way I understand it the get-request I'm sending from the browser is sent to the Figwheel-server, the origin of the site. I have no reason to believe that Figwheel knows anything about the http-handlers I've defined in the server file.

(defroutes routes
  (GET "/" _
    {:status 200
     :headers {"Content-Type" "text/html; charset=utf-8"}
     :body (io/input-stream (io/resource "public/index.html"))})
  (resources "/"))

(def http-handler
  (-> routes
      (wrap-defaults api-defaults)
      wrap-with-logger
      wrap-gzip))
like image 869
Sebastian Oberhoff Avatar asked Nov 09 '22 13:11

Sebastian Oberhoff


1 Answers

For a ClojureScript project (i.e. not Clojure), I believe you want this: https://github.com/r0man/cljs-http

like image 95
Alan Thompson Avatar answered Nov 15 '22 07:11

Alan Thompson