在 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);
}
相关推荐
小白杨树树1 小时前
【WebSocket】SpringBoot项目中使用WebSocket
spring boot·websocket·网络协议
云计算-Security2 小时前
如何理解 IP 数据报中的 TTL?
网络协议·tcp/ip
itachi-uchiha3 小时前
命令行以TLS/SSL显式加密方式访问FTP服务器
服务器·网络协议·ssl
稳联技术3 小时前
实践提炼,EtherNet/IP转PROFINET网关实现乳企数字化工厂增效
网络·网络协议·tcp/ip
Icoolkj4 小时前
WebRTC 与 WebSocket 的关联关系
websocket·网络协议·webrtc
红米饭配南瓜汤4 小时前
WebRTC中的几个Rtp*Sender
网络·网络协议·音视频·webrtc·媒体
前端老六喔6 小时前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
猫头虎6 小时前
[特殊字符]解决 “IDEA 登录失败。不支持早于 14.0 的 GitLab 版本” 问题的几种方法
java·ide·网络协议·http·https·gitlab·intellij-idea
醉书生ꦿ℘゜এ6 小时前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
扣丁梦想家7 小时前
✅ 常用 Java HTTP 客户端汇总及使用示例
java·开发语言·http