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



我确信我一定做错了什么。。。以下是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)))

当我从jquery:发送以下内容时,末尾的"println"将:val1的类型显示为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);
    }
});

那么我做错了什么?

这可能取决于jQuery请求,而不是环形中间件。

老实说,我对jQuery了解不多,但我刚刚找到了这个答案,看起来它可以解释发生了什么。简而言之,当前查询中的数据将被编码为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);
});

最新更新