一、获取 URL 参数
1. 路由参数
通过 `:` 来定义路由参数,使用 `req.params` 来获取路由参数。
const express = require("express");
const app = express();
const port = 3000;
// 定义路由,使用 :id 作为路由参数
app.get("/users/:id", (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
二、获取查询参数
1. 查询字符串参数
使用 `req.query` 来获取查询参数,这些参数通常出现在 URL 的 `?` 后面。访问 `http://localhost:3000/search?q=express` 时
app.get("/search", (req, res) => {
const query = req.query.q;
res.send(`Search query: ${query}`);
});
三、获取请求体参数
1. JSON 格式请求体
使用 `express.json()` 中间件解析 JSON 格式的请求体,使用 `req.body` 来获取请求体中的数据。
app.use(express.json());
app.post("/data", (req, res) => {
const data = req.body;
res.send(`Received data: ${JSON.stringify(data)}`);
});
四、获取表单数据
1. 表单数据(URL-encoded)
使用 `express.urlencoded()` 中间件解析 URL-encoded 格式的请求体,使用 `req.body` 来获取表单数据。
app.use(express.urlencoded({ extended: false }));
app.post("/form", (req, res) => {
const name = req.body.name;
const age = req.body.age;
res.send(`Name: ${name}, Age: ${age}`);
});
五、获取请求头参数
1. 请求头信息
使用 `req.headers` 来获取请求头信息。
app.get("/headers", (req, res) => {
const userAgent = req.headers["user-agent"];
res.send(`User Agent: ${userAgent}`);
});
六、总结
路由参数:使用 `req.params` 获取 URL 中定义的路由参数,例如 `/users/:id` 中的 `id`。
查询参数:使用 `req.query` 获取 URL 中 `?` 后的查询参数,例如 `/search?q=express` 中的 `q`。
请求体参数:`express.json()` 中间件获取 JSON 格式请求体,通过 `req.body` 访问。`express.urlencoded()` 中间件获取 URL-encoded 格式请求体,通过 `req.body` 访问。
请求头参数:使用 `req.headers` 获取请求头信息,例如 `req.headers['user-agent']`。
903

被折叠的 条评论
为什么被折叠?



