Using hunchentoot to parse a send request sent by model.save () to Backbone.js

I am new to javascript / web application and trying to implement my first web application using hunchentoot and backbone.js. The first thing I experimented with was understanding how the model.fetch () and model.save () functions work.

It seems to me that model.fetch () is launching a "GET" request, and model.save () is launching a "POST" request. So I wrote a simple handler in hunchentoot, as shown below:

(hunchentoot:define-easy-handler (dataset-handler :uri "/dataset") () (setf (hunchentoot:content-type*) "text/html") ;; get the request type, canbe :get or :post (let ((request-type (hunchentoot:request-method hunchentoot:*request*))) (cond ((eq request-type :get) (dataset-update) ;; return the json boject constructed by jsown (jsown:to-json (list :obj (cons "length" *dataset-size*) (cons "folder" *dataset-folder*) (cons "list" *dataset-list*)))) ((eq request-type :post) ;; have no idea on what to do here ....)))) 

It is designed to handle fetching / saving a model whose corresponding URL is "/ dataset". The fetch file works fine, but I'm confused by saving (). I saw that the "post" request was launched and processed using a simple handler, but the request seems to have only a meaningful header, I cannot find the actual json object hidden in the request. So my question is:

  • How can I get the json object from the post post that model.save () launched, so that a later json library (like jsown) can be used to parse it?
  • What should hunchentoot answer so that the client knows what to β€œsave” successfully?

I tried the post-parameters function in hunchentoot and it returns nil, and have not seen many people using hunchentoot + backbone.js with googling. It is also useful if you can direct me to some articles / blogs that help to understand how backbone.js save () works.

Thanks so much for your patience!

+4
source share
1 answer

Thanks to wvxvw comments, I found a solution to this question. object can be obtained by calling hunchentoot:raw-post-data . To be more detailed, first call (hunchentoot:raw-post-data :force-text t) to get the message data as a string, and then feed it to jsown:parse . The following is a complete simple handler:

 (hunchentoot:define-easy-handler (some-handler :uri "/some") () (setf (hunchentoot:content-type*) "text/html") (let ((request-type (hunchentoot:request-method hunchentoot:*request*))) (cond ((eq request-type :get) ... );; handle get request ((eq request-type :post) (let* ((data-string (hunchentoot:raw-post-data :force-text t)) (json-obj (jsown:parse data-string))) ;; use jsown to parse the string .... ;; play with json-obj data-string))))) ;; return the original post data string, so that the save() in backbone.js will be notified about the success. 

Hope this helps others who have the same confusion.

+6
source

Source: https://habr.com/ru/post/1438201/


All Articles