2013-07-27 23 views
2

我敢肯定,我一定是做錯了什麼......這裏是Clojure中的相關線路:ring.middleware.json/wrap-json-params將數字解析爲字符串?

(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))) 

的「的println」接近尾聲時顯示的類型:作爲java.lang.String中VAL1當我從jquery發送以下內容:

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

那麼我在做什麼錯了?

+1

我沒有在您的代碼中看到任何可能會發生這種情況的內容。我設置了一個簡單的例子來嘗試重現問題,但我無法做到。你能提供更多的細節嗎? – Jeremy

+0

嘗試使用cURL而不是jQuery並查看是否得到不同的結果。 – Jeremy

+0

我當然會。 – user1020853

回答

0

這可能歸結爲jQuery請求,而不是環形中間件。

說實話,我不太瞭解jQuery,但是我只是碰到了this answer,看起來它可以解釋發生了什麼。簡而言之,來自您的查詢的數據將在URL中被編碼爲字符串。這些將被解析爲字符串,而不是整數,因爲URL編碼沒有指定類型。如果你想要JSON編碼,你需要明確指定它。像這樣:

$.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); 
}); 
+0

你是對的。一旦我通過了這一點,我也遇到了其他一些問題。也就是說,當我像上面那樣設置contentType時,這不知道怎麼做到了環中間件。這有一個效果,即使我stringify()我的請求現在不會被解析。我最終做了上面的和一個非常像Ring的定製中間件。這對我來說工作正常,因爲還有其他處理我想要做。 – user1020853