概述
Express/Connect 中间件,解析 JSON、urlencoded、raw 与 text 请求体并挂载到 req.body。
核心 API
bodyParser.json:解析传入的 JSON 请求体并填充 req.body。bodyParser.urlencoded:解析 urlencoded 表单请求体,extended 为 true 时使用 qs 库。bodyParser.raw:将请求体缓冲为 Buffer,用于 webhook 签名校验。
使用注意
为 JSON 解析设置合理的 limit,避免超大请求体耗尽内存;strict 为 true 时只接受数组和对象,能拒绝顶层标量,减少误用。校验 webhook 签名时务必使用 raw 解析器保留原始字节,先验签再解析,防止在解析阶段被篡改。
验证方式
对成功、超大请求体、错误 Content-Type 三类场景编写测试,断言 req.body 的实际类型,并确认超过 limit 时返回 413。
版本提示
以上签名与用法以 v1.20 为基准,升级大版本前请对照官方迁移说明确认 API 是否变更。
代码示例
import bodyParser from 'body-parser';
app.use(bodyParser.json({ limit: '1mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/webhook', bodyParser.raw({ type: 'application/json' }));
npm install body-parser