2

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?

user1020853
  • 237
  • 3
  • 7
  • 1
    I don't see anything in your code that would case that to happen. I set up a simple example to try reproducing the issue, but I wasn't able to. Can you provide any more details? – Jeremy Jul 27 '13 at 18:08
  • Try using cURL instead of jQuery and see if you get different results. – Jeremy Jul 27 '13 at 20:02

1 Answers1

0

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);
});
Community
  • 1
  • 1
Daniel Neal
  • 4,165
  • 2
  • 20
  • 34
  • You are correct. I also had some other problems once I got past this point. Namely when I set contentType as you have above, this somehow wasn't getting through to the ring middleware. This had the effect that even if I stringify() my request would now not be parsed at all. I ended up doing the above along with a custom middleware very much like Ring's. This works fine for me, because there was other processing I wanted to do anyway. – user1020853 Aug 03 '13 at 12:49