处理请求与响应
掌握如何解析传入的请求数据并构建适当的 HTTP 响应,包括 JSON 和 HTML。
处理请求与响应 是 CoddyKit 上的免费 Clojure Functional Programming & JVM Backend Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clojure Functional Programming & JVM Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Handling Requests & Responses
In web development, your application constantly handles incoming requests from clients and sends back appropriate responses. This lesson teaches you how to read data from a client's request and construct different types of responses, like HTML and JSON, using Clojure's Ring.
Understanding the Ring Request Map
When a request hits your Clojure application, Ring transforms it into a standard Clojure map, often called the request map. This map contains all details about the incoming request, such as:
:uri: The path of the request (e.g.,"/users"):request-method: The HTTP method (e.g.,:get,:post):headers: A map of all HTTP headers:query-params: A map of URL query parameters:body: The request body, if any
Accessing Query & Form Parameters
Clients often send data via URL query parameters (e.g., /search?q=clojure) or HTML form parameters. Ring provides these parsed in the :query-params and :form-params keys of the request map, respectively. You can access them like any other map entry.
Code: Query Parameter Demo
Try running this example to see how to extract a query parameter. We'll simulate a request map for a handler function.
(ns coddykit.core
(:require [ring.util.response :refer [response]]))
(defn greet-handler [request]
(let [name (get-in request [:query-params "name"] "Guest")]
(response (str "Hello, " name "!"))))
(defn -main []
(let [mock-request {:query-params {"name" "Coddy"}}]
(println "Simulating request with name 'Coddy':")
(let [res (greet-handler mock-request)]
(println "Status:" (:status res))
(println "Body:" (:body res))))
(let [mock-request-no-name {:query-params {}}]
(println "\nSimulating request with no name:")
(let [res (greet-handler mock-request-no-name)]
(println "Status:" (:status res))
(println "Body:" (:body res))))Reading the Request Body
When clients send data in the request body (e.g., for POST or PUT requests), this data is available in the :body key of the request map. For common formats like JSON, you'll typically use a Ring middleware to parse the raw body into a Clojure map automatically. Without middleware, :body contains an InputStream.
Building Your Response Map
After processing a request, your handler function must return a response map. This map tells Ring how to construct the HTTP response sent back to the client. A minimal response map needs:
:status: The HTTP status code (e.g.,200for OK,404for Not Found):headers: A map of HTTP headers (e.g.,{"Content-Type" "text/html"}):body: The actual content to send back (e.g., HTML string, JSON string)
Responding with HTML
To send an HTML page, your response map's :body should be an HTML string, and the "Content-Type" header must be set to "text/html". Ring's response helper function is a great starting point, and header helps add headers.
Code: HTML Response Demo
Here's how to create a simple handler that responds with an HTML page. Note the use of header to set the correct content type.
(ns coddykit.core
(:require [ring.util.response :refer [response header]]))
(defn html-page-handler [request]
(-> (response "<h1>Welcome to CoddyKit!</h1><p>This is an HTML page.</p>")
(header "Content-Type" "text/html")))
(defn -main []
(let [mock-request {}]
(println "Simulating request for HTML page:")
(let [res (html-page-handler mock-request)]
(println "Status:" (:status res))
(println "Headers:" (:headers res))
(println "Body:" (:body res)))))Responding with JSON
For API endpoints, you'll often send data back as JSON. This requires setting the "Content-Type" header to "application/json" and ensuring your :body contains a valid JSON string. You'll typically use a library like clojure.data.json or cheshire to convert Clojure data structures into JSON strings.
Code: JSON Response Demo
This example shows how to send a JSON response. We use clojure.data.json to convert a Clojure map to a JSON string.
(ns coddykit.core
(:require [ring.util.response :refer [response header]]
[clojure.data.json :as json]))
(defn json-data-handler [request]
(let [data {:status "success" :message "Data received!"}]
(-> (response (json/write-str data))
(header "Content-Type" "application/json"))))
(defn -main []
(let [mock-request {}]
(println "Simulating request for JSON data:")
(let [res (json-data-handler mock-request)]
(println "Status:" (:status res))
(println "Headers:" (:headers res))
(println "Body:" (:body res)))))Quick Check: Response Structure
You're building an API and need to send a successful response with a JSON object {"message": "Item created"}. Which of the following correctly represents the Ring response map?
Recap: Requests & Responses
You've learned how to handle the core of web interactions in Clojure! We covered:
- The structure of the Ring request map and how to access its data.
- Extracting query and form parameters from requests.
- Understanding how request bodies (like JSON) are handled.
- Constructing Ring response maps with
:status,:headers, and:body. - Sending back both HTML and JSON content by setting the appropriate
Content-Typeheader.
These are fundamental skills for building any web application with Ring and Compojure!
常见问题解答
「处理请求与响应」课时是免费的吗?
是的 — 「处理请求与响应」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clojure Functional Programming & JVM Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。
「处理请求与响应」这节课中我会学到什么?
掌握如何解析传入的请求数据并构建适当的 HTTP 响应,包括 JSON 和 HTML。 你通过在浏览器中直接运行的动手代码来练习 Clojure Functional Programming & JVM Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Clojure Functional Programming & JVM Backend Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Clojure Functional Programming & JVM Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「处理请求与响应」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Clojure Functional Programming & JVM Backend Development 课中编写并运行代码吗?
能。每节 Clojure Functional Programming & JVM Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。