ring.middleware.json / wrap-json-params将数字解析为字符串?

时间:2013-07-27 13:38:45

标签: json clojure ring

我确信我一定做错了......这里是相关的行语:

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

当我从jquery发送以下内容时,接近结尾的“println”显示以下类型:val1 as java.lang.String:

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

那么我做错了什么?

1 个答案:

答案 0 :(得分: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);
});