【问题标题】:lein ring auto-refresh overwrites request body?lein ring 自动刷新覆盖请求正文?
【发布时间】:2015-06-02 01:22:08
【问题描述】:

我编写了简单的客户端-服务器应用程序,参考“ClojureScript:启动并运行”。

https://github.com/phaendal/clojure-simple-client-server

如下服务器代码所示,/text 将请求和正文打印到控制台并从(slurp (:body req)) 返回正文。

但如果project.clj 中的:auto-refresh? 设置为true(slurp (:body req)) 将返回空字符串而不是发送的值。

为什么它返回空?以及如何通过自动刷新获取请求正文?

(ns client-server.server
  (:gen-class)
  (:require [compojure.route :as route]
            [compojure.core :as compojure]
            [ring.util.response :as response]))

(defn simple-print [req]
  (let [body (slurp (:body req) :encoding "utf-8")]
    (println req)
    (println (str "slurped: " body))
    body))

(compojure/defroutes app
  (compojure/POST "/text" request (simple-print request))
  (compojure/GET "/" request
                 (-> "public/index.html"
                     (response/resource-response)
                     (response/content-type "text/html")
                     (response/charset "utf-8")))
  (route/resources "/"))

【问题讨论】:

    标签: clojure leiningen ring compojure


    【解决方案1】:

    当您设置auto-refresh: true 时,lein-ring 还会添加ring.middleware.paramswrap-params。见https://github.com/weavejester/ring-refresh/blob/master/src/ring/middleware/refresh.clj#L90-L102

    ring.middleware.params 通过slurp 排空请求正文来解析请求正文中的表单参数,就像您在处理程序中所做的那样。见https://github.com/mmcgrana/ring/blob/master/ring-core/src/ring/middleware/params.clj#L29

    因此,当您尝试在处理程序中啜饮它时,请求正文已经清空。

    另外,当您尝试 POST 时,请注意发送的内容类型。默认为application/www-form-urlencoded,它需要参数名称和值。见http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1

    只是像在 clojurescript 中那样发送纯值并不能很好地与表单参数解析器配合使用。在您的项目示例中,环参数中间件只是跳过它,因为从您的 javascript 发送的值不符合规范。如果您在 POST 请求中输入名称和值,它会显示在请求中的 :params 键中。

    【讨论】:

    • 有道理!我在 xhr/send header-option 发送了带有(clj->js {"Content-Type" "text/plain"}) 的纯文本,它可以工作。还发布数据(str "text=" expr-str) 无标题作品。谢谢。
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2013-03-25
    • 2016-03-26
    • 2013-12-31
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多