解析请求体

在 Web 开发中,客户端向服务器发送的请求通常会包含请求体(Request Body),其中包含了用户提交的数据。Express 提供了多种中间件来解析不同格式的请求体,常见的格式包括 JSON 数据、URL 编码的表单数据以及多部分表单数据。

使用中间件解析请求体

1. 解析 JSON 数据

客户端可以使用 application/json 格式将数据发送到服务器。在 Express 中,我们可以使用 express.json() 中间件来解析 JSON 格式的请求体。

1.1 安装并配置 JSON 中间件

const express = require('express');
const app = express();

// 使用 express.json() 中间件解析请求体中的 JSON 数据
app.use(express.json());

`

1.2 处理 POST 请求并解析 JSON 数据

app.post('/json', (req, res) => {
  // 获取请求体中的 JSON 数据
  const { name, age } = req.body;
  res.send(`收到的用户数据:姓名 ${name},年龄 ${age}`);
});

1.3 测试

客户端发送一个 POST 请求,内容为 JSON 格式:

{
  "name": "张三",
  "age": 28
}

服务器会解析并返回响应:

收到的用户数据:姓名 张三,年龄 28

2. 解析 URL 编码的表单数据

当用户通过传统的 HTML 表单提交数据时,浏览器会以 application/x-www-form-urlencoded 格式发送数据。Express 提供了 express.urlencoded() 中间件来解析这种格式的数据。

2.1 安装并配置 URL 编码中间件

// 使用 express.urlencoded() 中间件解析 URL 编码的表单数据
app.use(express.urlencoded({ extended: true }));

extended: true 选项允许你解析嵌套的对象,推荐使用此配置。

2.2 处理 POST 请求并解析表单数据

app.post('/form', (req, res) => {
  // 获取表单中的数据
  const { username, password } = req.body;
  res.send(`表单提交的数据:用户名 ${username},密码 ${password}`);
});

2.3 测试

客户端通过表单提交:

<form action="/form" method="POST">
  <label for="username">用户名:</label>
  <input type="text" id="username" name="username" required />
  <br />
  <label for="password">密码:</label>
  <input type="password" id="password" name="password" required />
  <br />
  <button type="submit">提交</button>
</form>

服务器接收到请求后,会解析并返回:

表单提交的数据:用户名 张三,密码 123456

3. 解析多部分表单数据(文件上传)

如果表单包含文件上传,浏览器会以 multipart/form-data 格式提交请求。为了处理这种请求,需要使用第三方中间件,如 multer

3.1 安装 multer

npm install multer

3.2 配置 multer 处理文件上传

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
  // 获取上传的文件信息
  const file = req.file;
  res.send(`文件上传成功!文件名:${file.originalname}`);
});

3.3 测试

创建一个 HTML 表单,允许用户选择文件并上传:

<form action="/upload" method="POST" enctype="multipart/form-data">
  <label for="file">选择文件:</label>
  <input type="file" id="file" name="file" required />
  <br />
  <button type="submit">上传</button>
</form>

4. 总结

Express 提供了非常简便的中间件来解析不同格式的请求体,包括:

  • express.json() 用于解析 JSON 格式的数据;
  • express.urlencoded() 用于解析 URL 编码的表单数据;
  • multer 用于处理文件上传的多部分表单数据。

通过正确配置这些中间件,我们可以轻松地处理来自客户端的各种请求体数据,并根据需求进行处理和响应。