在 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);
}