查看: 318|回复: 1

HTTP请求传参方式详解:路径参数、查询参数、表单编码、JSON与文件上传

[复制链接]
发表于 3 小时前 | 显示全部楼层 |阅读模式
在实际的 Web 开发中,客户端向服务端传递数据的方式有多种选择,不同的场景需要采用不同的传参方式。本文介绍五种最常见的 HTTP 请求传参形式:路径参数、查询参数、application/x-www-form-urlencoded、application/json 和 multipart/form-data,并基于 Express 框架给出完整的服务端处理代码,方便读者在本地测试验证。

一、路径参数(Route Parameters)
路径参数直接将值嵌入 URL 路径中,常用于标识具体资源,如用户 ID、商品 ID 等。例如 GET /users/123,其中 123 就是路径参数。在 Express 中通过路由占位符 :id 定义,服务端使用 req.params 获取。
  1. // 服务端路由定义
  2. app.get('/users/:id', (req, res) => {
  3.   const userId = req.params.id;
  4.   res.json({ message: '获取用户信息', userId });
  5. });
复制代码

二、查询参数(Query Parameters)
查询参数附加在 URL 的问号 ? 之后,多个参数用 & 连接,常见于搜索、过滤、分页等场景。例如 GET /search?keyword=node&page=2。Express 通过 req.query 获取所有查询参数。
  1. app.get('/search', (req, res) => {
  2.   const { keyword, page } = req.query;
  3.   res.json({ message: '查询参数已接收', keyword, page: page || 1 });
  4. });
复制代码

三、application/x-www-form-urlencoded
这是 HTML 表单默认的编码方式(method="post" 且未指定 enctype 时)。提交时浏览器将表单字段编码为 key=value&key2=value2 的形式,放入请求体。服务端需使用 express.urlencoded() 中间件解析。
  1. // 前端表单(示例)
  2. <form action="/register" method="post">
  3.   <input type="text" name="username" />
  4.   <input type="password" name="password" />
  5.   <button>submit</button>
  6. </form>
  7. // 服务端处理
  8. app.use(express.urlencoded({ extended: true }));
  9. app.post('/register', (req, res) => {
  10.   const { username, password } = req.body;
  11.   res.json({ username, password });
  12. });
复制代码

四、application/json
RESTful API 常用 JSON 格式传输复杂数据结构。前端需要设置 Content-Type: application/json,并将 JavaScript 对象序列化为 JSON 字符串。服务端使用 express.json() 中间件解析。
  1. // 前端用 fetch 发送 JSON 请求
  2. fetch('/login', {
  3.   method: 'POST',
  4.   headers: { 'Content-Type': 'application/json' },
  5.   body: JSON.stringify({ username: 'admin', password: '123456' })
  6. });
  7. // 服务端处理
  8. app.use(express.json());
  9. app.post('/login', (req, res) => {
  10.   const { username, password } = req.body;
  11.   res.json({ username, password });
  12. });
复制代码

五、multipart/form-data
文件上传必须使用 multipart/form-data,同时也可以提交普通表单字段。表单需设置 enctype="multipart/form-data",浏览器会自动生成 Content-Type 并包含 boundary 分隔符。服务端使用 multer 等中间件处理。
  1. // 前端表单(需指定 enctype)
  2. <form action="/upload" method="post" enctype="multipart/form-data">
  3.   <input type="file" name="avatar" />
  4.   <input type="text" name="username" />
  5.   <input type="password" name="password" />
  6.   <button>submit</button>
  7. </form>
  8. // 服务端处理(需安装 multer)
  9. const multer = require('multer');
  10. const upload = multer({ storage: multer.memoryStorage() });
  11. app.post('/upload', upload.single('avatar'), (req, res) => {
  12.   // req.file 包含上传文件信息,req.body 包含文本字段
  13.   res.json({
  14.     message: '文件上传成功',
  15.     filename: req.file.originalname,
  16.     size: req.file.size,
  17.     mimetype: req.file.mimetype
  18.   });
  19. });
复制代码

完整 Express 服务端示例
下面整合上述五种传参方式的处理逻辑,提供一个可直接运行的本地服务器。
  1. const express = require('express');
  2. const cors = require('cors');
  3. const multer = require('multer');
  4. const app = express();
  5. const port = 3000;
  6. app.use(cors());
  7. // 解析 JSON 和 URL 编码的请求体
  8. app.use(express.json());
  9. app.use(express.urlencoded({ extended: true }));
  10. // 1. 路径参数
  11. app.get('/users/:id', (req, res) => {
  12.   res.json({ message: '获取用户信息', userId: req.params.id });
  13. });
  14. // 2. 查询参数
  15. app.get('/search', (req, res) => {
  16.   const { keyword, page } = req.query;
  17.   res.json({ message: '查询参数已接收', keyword, page: page || 1 });
  18. });
  19. // 3. URL 编码表单
  20. app.post('/register', (req, res) => {
  21.   const { username, password } = req.body;
  22.   res.json({ username, password });
  23. });
  24. // 4. JSON 请求体
  25. app.post('/login', (req, res) => {
  26.   const { username, password } = req.body;
  27.   res.json({ username, password });
  28. });
  29. // 5. 文件上传(multipart)
  30. const upload = multer({ storage: multer.memoryStorage() });
  31. app.post('/upload', upload.single('avatar'), (req, res) => {
  32.   res.json({
  33.     message: '文件上传成功',
  34.     filename: req.file.originalname,
  35.     size: req.file.size,
  36.     mimetype: req.file.mimetype
  37.   });
  38. });
  39. app.listen(port, () => {
  40.   console.log(`服务器启动:http://localhost:${port}`);
  41. });
复制代码

测试方法
将上述代码保存为 server.js,依次执行以下命令初始化项目并安装依赖:
  1. npm init -y
  2. npm i express cors multer
  3. node server.js
复制代码
服务启动后,可以使用浏览器、Postman 或 curl 发送对应请求,观察服务端返回的 JSON 数据以及终端输出的日志。通过实际测试,可以更直观地理解不同传参方式在客户端构造和服务端接收上的差异。
回复

使用道具 举报

发表于 3 小时前 | 显示全部楼层

Re: HTTP请求传参方式详解:路径参数、查询参数、表单编码、JSON与文件上传

非常详实的总结,感谢楼主分享!对初学者能快速分清几种传参方式很有帮助。之前在`urlencoded`和`json`的选择上有点模糊,看完清晰多了。另外提醒一下,如果文件上传要持久化到磁盘,`multer`的`diskStorage`可以指定保存路径,楼主给的`memoryStorage`适合临时处理或转存到云存储。收藏了!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-6-12 11:10 , Processed in 0.032491 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部