nodejs获取请求体的中间件 body-parse

152 阅读1分钟

虽然 Express 4.16.0 之后已经内置了处理请求体的功能(express.json()express.urlencoded()),但你也可以单独使用老牌中间件 body-parser,它仍然很常用,尤其在某些旧项目中。


📦 一、安装 body-parser

npm install body-parser

🧠 二、body-parser 常用中间件

const bodyParser = require('body-parser');

1. 解析 JSON 请求体

app.use(bodyParser.json());

📌 Content-Type: application/json

{
  "username": "tom",
  "password": "123"
}

2. 解析表单请求体(URL 编码格式)

app.use(bodyParser.urlencoded({ extended: true }));

📌 Content-Type: application/x-www-form-urlencoded

username=tom&password=123
  • extended: false 使用 querystring 解析器(不支持嵌套对象)
  • extended: true 使用 qs 模块(支持嵌套对象)

3. 其他类型(较少用)

  • bodyParser.raw():处理 application/octet-stream
  • bodyParser.text():处理 text/plain

✅ 三、完整示例

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// 注册 body-parser 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 处理 JSON 请求
app.post('/json', (req, res) => {
  console.log(req.body);
  res.send(`收到 JSON 数据:${JSON.stringify(req.body)}`);
});

// 处理表单请求
app.post('/form', (req, res) => {
  console.log(req.body);
  res.send(`收到表单数据:${JSON.stringify(req.body)}`);
});

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

🤔 四、body-parser vs express 内置中间件

特性body-parserexpress 内置(推荐)
是否需安装✅ 是❌ 无需额外安装
兼容旧项目✅ 支持老项目✅ 支持新项目
维护情况🔁 稳定但不再活跃更新✅ Express 官方维护
适合用在哪老旧项目、精细控制场景新项目直接用 express.xxx