在 Node.js 中使用原生 `http` 模块,获取请求的各个部分:**请求行、请求头、请求体、请求路径、查询字符串** 等内容

在 Node.js 中使用原生 http 模块,可以通过 req 对象来获取请求的各个部分:请求行、请求头、请求体、请求路径、查询字符串 等内容。


✅ 一、基础结构

js 复制代码
const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  // 解析 URL
  const parsedUrl = url.parse(req.url, true); // 第二个参数为 true 会自动解析 query

  // 请求行(method + URL)
  const method = req.method;
  const fullUrl = req.url;

  // 请求路径
  const pathname = parsedUrl.pathname;

  // 查询字符串(对象形式)
  const query = parsedUrl.query;

  // 请求头
  const headers = req.headers;

  // 请求体(需要手动拼接)
  let body = '';
  req.on('data', chunk => {
    body += chunk;
  });

  req.on('end', () => {
    console.log('--- 请求信息 ---');
    console.log('请求方法:', method);
    console.log('请求路径:', pathname);
    console.log('查询参数:', query);
    console.log('请求头:', headers);
    console.log('请求体:', body);

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ code: 0, msg: 'OK' }));
  });
});

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

✅ 二、字段说明

内容 获取方式 说明
请求方法 req.method 如 GET、POST、PUT 等
请求完整路径 req.url 包括 ?query=xxx
请求路径 url.parse(req.url).pathname 去除 query 的纯路径
查询字符串 url.parse(req.url, true).query 自动解析为对象
请求头 req.headers 是一个对象,所有 header 键小写
请求体 手动拼接监听 data / end 仅 POST/PUT 等方法时有数据

✅ 三、示例请求

请求:

http 复制代码
POST /user?id=100&name=tom HTTP/1.1
Host: localhost:3000
Content-Type: application/json

{
  "age": 20
}

打印结果:

js 复制代码
请求方法: POST
请求路径: /user
查询参数: { id: '100', name: 'tom' }
请求头: {
  host: 'localhost:3000',
  'content-type': 'application/json',
  ...
}
请求体: { "age": 20 }

✅ 四、如果你想处理 JSON 请求体

可以加个判断来解析:

js 复制代码
if (headers['content-type'] === 'application/json') {
  const data = JSON.parse(body);
  console.log('解析后的 JSON 数据:', data);
}
相关推荐
RoyLin1 天前
TypeScript设计模式:原型模式
前端·后端·node.js
RoyLin1 天前
TypeScript设计模式:单例模式
前端·后端·node.js
RoyLin1 天前
TypeScript设计模式:工厂方法模式
前端·后端·node.js
RoyLin1 天前
TypeScript设计模式:模板方法模式
前端·后端·node.js
moonless02221 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
RoyLin2 天前
TypeScript设计模式:适配器模式
前端·后端·node.js
RoyLin2 天前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
前端双越老师2 天前
2025 年还有前端不会 Nodejs ?
node.js·agent·全栈
FPGA_Linuxer2 天前
FPGA 40 DAC线缆和光模块带光纤实现40G UDP差异
网络协议·fpga开发·udp
real 12 天前
传输层协议UDP
网络·网络协议·udp