处理请求数据:正文、查询与参数
掌握 Express 如何接收并解析客户端传入的数据,包括路由参数、查询字符串、JSON 正文和表单提交。
处理请求数据:正文、查询与参数 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Where Client Data Comes From
An HTTP request can carry data in several places. An Express handler reads each from a different property of the req object:
- Route params:
req.params - Query string:
req.query - Request body:
req.body - Headers:
req.headers
app.get('/info', (req, res) => {
res.json({ params: req.params, query: req.query });
});Route Parameters
Route parameters are named URL segments prefixed with a colon. For /users/:id, a request to /users/42 gives req.params.id === '42'.
They are always strings, so convert to numbers when needed.
app.get('/users/:id', (req, res) => {
const id = Number(req.params.id);
res.send('Looking up user ' + id);
});Multiple Route Parameters
A route can capture several params at once. Each colon segment becomes a key on req.params.
app.get('/books/:author/:title', (req, res) => {
const { author, title } = req.params;
res.send(author + ' wrote ' + title);
});Query Strings
Everything after the ? in a URL is the query string. Express parses it into req.query as key-value pairs.
For /search?term=node&page=2, you get req.query.term and req.query.page.
app.get('/search', (req, res) => {
const { term, page } = req.query;
res.send('Searching ' + term + ' page ' + (page || 1));
});Parsing JSON Bodies
POST and PUT requests usually send a JSON body. Express does not parse it by default — you must enable the built-in middleware express.json().
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
res.json({ received: req.body });
});Parsing Form Data
HTML forms submit data as application/x-www-form-urlencoded. Enable express.urlencoded() to populate req.body from form fields.
app.use(express.urlencoded({ extended: true }));
app.post('/login', (req, res) => {
res.send('Welcome ' + req.body.username);
});Validating Required Fields
Never trust client input. Always check that required fields are present before using them, and respond with a 400 Bad Request if something is missing.
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'name and email required' });
}
res.status(201).json({ name, email });
});Reading Headers
Headers carry metadata like authentication tokens and content types. Access them via req.headers (keys are lowercased) or the helper req.get().
app.get('/secure', (req, res) => {
const auth = req.get('Authorization');
res.send('Token: ' + (auth || 'none'));
});Default Values for Optional Data
Query and body values are often optional. Provide sensible defaults so your handler does not break when a parameter is omitted.
app.get('/products', (req, res) => {
const page = Number(req.query.page) || 1;
const limit = Number(req.query.limit) || 10;
res.json({ page, limit });
});Combining All Three Sources
A single endpoint can read params, query, and body together. For example, updating a resource identified by a param, with options in the query, and new data in the body.
app.put('/users/:id', (req, res) => {
const id = req.params.id;
const notify = req.query.notify === 'true';
const updates = req.body;
res.json({ id, notify, updates });
});Common Mistakes
Watch out for these pitfalls:
- Forgetting
express.json()soreq.bodyisundefined - Treating params as numbers without converting
- Trusting input without validation
- Confusing query (
?key=value) with params (/:key)
Quick Check
Test your knowledge of Express request data.
Recap
You now know how Express receives client data:
req.paramsfor named URL segmentsreq.queryfor the query stringreq.bodyfor JSON (withexpress.json()) and forms (withexpress.urlencoded())req.headers/req.get()for metadata
Always validate and provide defaults — never trust raw client input.
常见问题解答
「处理请求数据:正文、查询与参数」课时是免费的吗?
是的 — 「处理请求数据:正文、查询与参数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「处理请求数据:正文、查询与参数」这节课中我会学到什么?
掌握 Express 如何接收并解析客户端传入的数据,包括路由参数、查询字符串、JSON 正文和表单提交。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「处理请求数据:正文、查询与参数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Express.js 框架基础
- Express 中的路由与中间件
- 设计 RESTful API 端点
- 处理请求数据:正文、查询与参数