一、HTTP 模块
1. 创建 HTTP 服务器
基本服务器示例
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
请求对象 (http.IncomingMessage)
-
req.method
: HTTP 请求方法 (GET, POST 等) -
req.url
: 请求的 URL 路径 -
req.headers
: 请求头对象 -
req.on('data', chunk => {})
: 接收请求体数据 -
req.on('end', () => {})
: 请求体接收完成
响应对象 (http.ServerResponse)
-
res.statusCode
: 设置状态码 -
res.setHeader(name, value)
: 设置响应头 -
res.writeHead(statusCode, headers)
: 组合设置状态码和头 -
res.write(data)
: 写入响应体 -
res.end([data])
: 结束响应
2. 发起 HTTP 请求
使用 http.request()
const options = {
hostname: 'example.com',
port: 80,
path: '/api/data',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();
简化方法 http.get()
http.get('http://example.com/api/data', (res) => {
// 处理响应...
});
二、HTTPS 模块
1. 创建 HTTPS 服务器
基本服务器示例
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Secure Hello World\n');
});
server.listen(443, () => {
console.log('HTTPS server running on port 443');
});
证书要求
-
key
: 私钥文件 -
cert
: 公钥证书 -
可选
ca
: 证书颁发机构链
2. 发起 HTTPS 请求
使用 https.request()
const options = {
hostname: 'api.example.com',
port: 443,
path: '/secure-data',
method: 'GET',
// 如需验证特定证书可添加以下选项
// ca: fs.readFileSync('ca-cert.pem'),
// rejectUnauthorized: true
};
const req = https.request(options, (res) => {
// 处理响应...
});
req.end();
简化方法 https.get()
https.get('https://api.example.com/secure-data', (res) => {
// 处理响应...
});
三、核心区别与特性对比
特性 | HTTP 模块 | HTTPS 模块 |
---|---|---|
协议 | HTTP | HTTPS |
默认端口 | 80 | 443 |
安全性 | 明文传输 | SSL/TLS 加密 |
性能开销 | 较低 | 较高 (加密/解密开销) |
证书要求 | 不需要 | 需要服务器证书 |
创建服务器 | http.createServer() |
https.createServer(options) |
客户端请求 | http.request() /http.get() |
https.request() /https.get() |
四、高级特性
1. 代理服务器实现
http.createServer((clientReq, clientRes) => {
const options = {
hostname: 'target.server.com',
port: 80,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
};
const proxy = http.request(options, (targetRes) => {
clientRes.writeHead(targetRes.statusCode, targetRes.headers);
targetRes.pipe(clientRes);
});
clientReq.pipe(proxy);
}).listen(8080);
2. 处理文件上传
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/upload') {
const fileData = [];
req.on('data', chunk => {
fileData.push(chunk);
});
req.on('end', () => {
const buffer = Buffer.concat(fileData);
fs.writeFile('uploaded.file', buffer, (err) => {
res.end(err ? 'Upload failed' : 'Upload successful');
});
});
}
});
3. 连接超时处理
const request = https.request(options, response => {
// 正常处理...
});
request.setTimeout(5000, () => {
request.abort();
console.log('Request timed out');
});
request.on('error', err => {
if (err.code === 'ECONNRESET') {
console.log('Timeout caused connection reset');
}
});
五、最佳实践
1. 安全实践
-
始终验证 HTTPS 证书 (生产环境设置
rejectUnauthorized: true
) -
限制请求头大小防止内存耗尽
-
使用最新 TLS 版本 (在 Node.js 中通过
secureProtocol
选项) -
正确处理连接终止和超时
2. 性能优化
-
重用 TCP 连接 (Keep-Alive)
-
使用流式处理大文件
-
合理设置并发连接数
-
启用压缩 (通过
Accept-Encoding
头)
3. 错误处理
const server = http.createServer((req, res) => {
// ...处理逻辑
});
server.on('clientError', (err, socket) => {
if (err.code === 'ECONNRESET' || !socket.writable) return;
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
// 优雅关闭服务器
server.close(() => process.exit(1));
});
六、实际应用场景
1. Web 应用服务器
-
结合 Express/Koa 等框架
-
实现 RESTful API
-
处理静态文件服务
2. 微服务通信
-
服务间 HTTP 调用
-
健康检查端点
-
服务发现集成
3. 代理和网关
-
反向代理实现
-
API 网关路由
-
请求/响应转换
4. Webhook 接收
-
处理第三方服务回调
-
实时事件通知
-
数据同步端点
Node.js 的 http 和 https 模块提供了构建网络应用的基础能力,理解它们的核心原理和特性对于开发高性能、安全的网络服务至关重要。在实际项目中,通常会结合上层框架使用,但底层原理仍然基于这些核心模块。