req(请求对象,在 Express.js 中)包含内容意义

req(请求对象)包含了客户端发起的 HTTP 请求的所有信息

如router.get('/:year', authenticate, async (req, res) => {}) 这个路由中,你可以从 req 中获取以下常见内容:

1. 路由参数(URL 中的动态段)

由于定义了 /:year,可以通过 req.params 获取:

const year = req.params.year;   // 例如:2026

如果有多个参数如 /user/:userId/post/:postId,则 req.params = { userId: '...', postId: '...' }。

2. 查询字符串参数(Query String)

如 ?page=1&size=10,可以通过 req.query 获取:

const page = req.query.page;    // '1'(字符串)
const size = req.query.size;    // '10'

注意:值都是字符串,需要自行转换数字。

3. 请求头(Headers)

通过 req.headers 获取所有请求头,键名自动转为小写:

const contentType = req.headers['content-type'];
const token = req.headers.authorization;

4. 请求体(Body)—— 注意 GET 请求通常没有 Body

虽然 GET 请求不应该携带请求体,但技术上可以发送,Express 仍然能解析(需配置 express.json() 等中间件)。不过规范上不建议。如果确实需要读取,可使用:

const body = req.body;   // 需要 body-parsing 中间件

5. HTTP 方法、URL、原始路径等

const method = req.method;       // 'GET'
const url = req.url;             // '/2026?page=1'
const originalUrl = req.originalUrl; // 与 url 类似,但包含原始路径
const baseUrl = req.baseUrl;     // 挂载子应用时的前缀
const path = req.path;           // '/2026'

6. 客户端信息

const ip = req.ip;               // 客户端 IP 地址
const ips = req.ips;             // 如果信任代理,则包含 IP 列表
const hostname = req.hostname;   // 主机名(不包含端口)
const protocol = req.protocol;   // 'http' 或 'https'

7. 文件上传(如果使用了 multer 等中间件)

const files = req.files;         // 上传的文件
const file = req.file;           // 单个文件
const cookies = req.cookies;     // 解析后的 Cookie 对象
const signedCookies = req.signedCookies; // 签名的 Cookie

9. Session(如果使用了 express-session 中间件)

const userId = req.session.userId;

10. 认证中间件附加的信息(如 authenticate)

通常在 authenticate 中间件中,验证成功后会将用户信息挂载到 req 对象上,常见属性:

const user = req.user;           // 用户对象(例如 Passport.js 默认挂载)
const userId = req.userId;       // 自定义挂载的用户ID
const isAuthenticated = req.isAuthenticated(); // Passport 方法

你的 authenticate 中间件具体添加了什么属性,取决于它的实现。

11. 其他 Express 提供的属性/方法

req.get('Content-Type');          // 获取指定请求头,等同于 req.headers['content-type']
req.is('json');                   // 检查请求的 Content-Type 是否为 JSON
req.accepts('html');              // 检查客户端接受哪种响应类型
req.range(100);                   // 解析 Range 头

12. 原始请求对象(Node.js 原生 http.IncomingMessage)

const rawReq = req;               // Express 的 req 继承了原生对象
// 例如获取 socket:req.socket
// 例如获取原始数据:req.on('data', ...) 但通常用 body-parser 处理

总结:在你的 GET /:year 路由中最常用的

router.get('/:year', authenticate, async (req, res) => {
    const year = req.params.year;           // 路径中的年份
    const { page, limit } = req.query;      // 查询参数
    const user = req.user;                  // 由 authenticate 中间件添加
    const ip = req.ip;                      // 客户端 IP
    // ...
});

由于是 GET 请求,req.body 通常为空或未定义。如果有其他中间件(如 express.json())配置,也能解析,但不符合 HTTP 语义。

posted @ 2026-06-01 16:04  冀未然  阅读(23)  评论(0)    收藏  举报