在 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);
}
相关推荐
浪遏6 小时前
recruitment-cli:让 AI 接手求职招聘,从架构到一次发送超时
架构·typescript·node.js
略懂而已18 小时前
安装SSL后网站速度变慢?
网络·网络协议·ssl
Thanks_ks1 天前
HTTPS:浏览器地址栏那把锁的工作原理
http·网络安全·https·tls·加密算法·数字证书·中间人攻击
杨凯凡1 天前
Spring Boot 大文件下载如何实现断点续传?HTTP Range、206 与 416 实战
spring boot·后端·http
吴建旭 智宅焕1 天前
智能家居全国交付中执行端能力跃迁的架构设计:从标准装调到交付专家的系统化路径
网络·网络协议·智能家居
Dream Cosmos2 天前
传输层协议之UDP
网络·网络协议·udp
沉默小管2 天前
我用 NestJS + Nuxt 3 做了个导航站,聊几个踩过的坑
node.js·seo
梦到啥说啥2 天前
Linux网络编程:UDP网络协议
linux·网络协议·udp
FungLeo2 天前
成为全栈·Vue 管理后台篇·用 fetch 建一层可控的请求内核
前端·javascript·vue.js·http·fetch·formdata·接口封装
张小姐的猫2 天前
【基于 WebSocket 的多用户网页五子棋】—— 项目结构设计与实用工具类模块
网络·websocket·网络协议