您现在的位置是:网站首页 > HTTP模块详解文章详情
HTTP模块详解
陈川
【
Node.js
】
63054人已围观
3871字
Node.js的HTTP模块是构建网络应用的核心工具之一,它提供了创建服务器和客户端的能力,支持HTTP协议的基本操作。无论是处理请求、响应数据,还是与外部API交互,HTTP模块都能高效完成任务。
HTTP模块基础
HTTP模块通过require('http')
引入,核心功能分为服务器和客户端两部分。服务器通过http.createServer()
创建,客户端通过http.request()
或http.get()
发起请求。
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
res.end('Hello World');
});
server.listen(3000);
创建HTTP服务器
服务器实例通过监听端口处理请求。createServer
的回调函数接收req
(请求对象)和res
(响应对象)两个参数。请求对象包含URL、方法、头信息等,响应对象用于设置状态码、头信息和返回数据。
const server = http.createServer((req, res) => {
// 获取请求方法
console.log(req.method); // GET/POST等
// 设置响应头
res.setHeader('Content-Type', 'text/html');
// 返回JSON数据
if (req.url === '/api') {
res.end(JSON.stringify({ data: 'API Response' }));
} else {
res.end('<h1>Home Page</h1>');
}
});
处理请求与响应
请求对象解析
req.url
:获取请求路径(如/user?id=1
)req.method
:请求方法(GET/POST等)req.headers
:请求头信息(对象形式)
响应控制
res.writeHead(statusCode, headers)
:一次性写入状态码和头信息res.write(data)
:分段发送数据(适用于大文件)res.end()
:结束响应(必须调用)
// 流式响应示例
fs.createReadStream('large-file.txt').pipe(res);
HTTP客户端
通过http.request()
或简化的http.get()
发起HTTP请求,适用于调用外部API或服务间通信。
// GET请求示例
http.get('http://example.com/api', (response) => {
let data = '';
response.on('data', (chunk) => data += chunk);
response.on('end', () => console.log(data));
});
// POST请求示例
const options = {
hostname: 'example.com',
path: '/api',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
};
const req = http.request(options, (res) => {
res.on('data', (d) => process.stdout.write(d));
});
req.write(JSON.stringify({ key: 'value' }));
req.end();
高级特性
超时控制
服务器和客户端均可设置超时:
server.timeout = 5000; // 5秒无活动断开连接
req.setTimeout(3000, () => req.abort()); // 客户端超时处理
代理与隧道
通过agent
属性实现连接池管理和代理:
const agent = new http.Agent({
keepAlive: true,
maxSockets: 10
});
http.get({ host: 'example.com', agent }, (res) => {});
HTTPS支持
需引入https
模块,配置证书后使用:
const https = require('https');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, (req, res) => {}).listen(443);
性能优化
- 连接复用:启用
keepAlive
减少TCP握手 - 管道化请求:HTTP/1.1支持管道化(需服务器支持)
- 缓冲区管理:合理设置
highWaterMark
控制内存使用
// 高并发优化示例
const server = http.createServer({
maxHeadersCount: 20,
requestTimeout: 10000
}, (req, res) => {});
错误处理
HTTP模块错误通过事件机制捕获:
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
req.on('error', (e) => {
console.error(`请求出错: ${e.message}`);
});
实际应用场景
REST API服务
const server = http.createServer((req, res) => {
const [path, query] = req.url.split('?');
if (req.method === 'GET' && path === '/users') {
const id = new URLSearchParams(query).get('id');
res.end(JSON.stringify(getUser(id)));
}
});
文件上传服务
结合multipart/form-data
解析:
const busboy = require('busboy');
server.on('request', (req, res) => {
if (req.method === 'POST') {
const bb = busboy({ headers: req.headers });
bb.on('file', (name, file, info) => {
file.pipe(fs.createWriteStream(info.filename));
});
req.pipe(bb);
}
});
WebSocket升级
HTTP服务器可升级为WebSocket:
server.on('upgrade', (req, socket, head) => {
wsServer.handleUpgrade(req, socket, head, (ws) => {
wsServer.emit('connection', ws, req);
});
});
与Express等框架对比
原生HTTP模块相比Express等框架:
- 优势:更轻量、无依赖、性能更高
- 劣势:需手动处理路由、中间件等逻辑
// Express等效代码对比
app.get('/api', (req, res) => res.json({ data: 'API' }));
// 原生实现
if (req.method === 'GET' && req.url === '/api') {
res.end(JSON.stringify({ data: 'API' }));
}
上一篇: 大数据可视化方案
下一篇: HTTPS与安全通信