Question

I'm sure I must be doing something wrong...here are the relevant lines of clojure:

(ns command.command-server
  (:use [org.httpkit.server :only [run-server]])
  (:use [storage.core-storage])
  (:use compojure.core)
  (:use [command.event-loop :only [enqueue]])
  (:require [compojure.handler :as handler]
            [compojure.route :as route]
            [ring.middleware.json :as middleware]))


(def app
  (-> (handler/api app-routes)
    (middleware/wrap-json-body)
    (middleware/wrap-json-response)
    (middleware/wrap-json-params)))


;in app-routes, the rest left out for brevity
  (POST "/request" {json :params} 
        (do              
          (queue-request json)
          (response {:status 200})
          ))

(defn queue-request [evt]
  (let [new-evt (assoc evt :type (keyword (:type evt)))]
    (println (str (type (:val1 evt)))) 
    (enqueue new-evt)))

The "println" near the end is showing the type of :val1 as java.lang.String when I send the following from jquery:

$.ajax({
    type: "POST",
    url: 'http://localhost:9090/request',
    data: {type: 'add-request', val1: 12, val2: 50},
    success: function(data){
        console.log(data);
    }
});

So what am I doing wrong?

Was it helpful?

Solution

This could be down to the jQuery request, rather than the ring middleware.

To be honest, I don't know much about jQuery, but I just came across this answer which looks like it could explain what's happening. In short, the data from your query as it stands will be encoded as strings in the URL. These will be parsed by ring into strings, not integers, as the URL encoding does not specify the type. If you want JSON encoding, you'll need to specify it explicitly. Like so:

$.ajax({
    type: "POST",
    url: 'http://localhost:9090/request',
    data: JSON.stringify({type: 'add-request', val1: 12, val2: 50}),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data){
    console.log(data);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top