1. 核心模块对比
特性 | http 模块 (HTTP/1.1) |
http2 模块 (HTTP/2) |
---|---|---|
协议版本 | HTTP/1.1(文本协议) | HTTP/2(二进制协议) |
多路复用 | 不支持(需多个 TCP 连接) | 支持(单连接多流) |
头部压缩 | 无 | HPACK 压缩算法 |
服务器推送 | 不支持 | 支持 |
TLS 依赖 | 可选(但生产环境建议启用) | 强制要求 TLS(可通过 allowHTTP1 降级) |
Node.js 版本 | 所有版本 | 8.4.0+(实验性),10.0.0+(稳定) |
2. 使用场景
http
模块:- 传统 HTTP/1.1 服务
- 简单请求/响应模型
- 需要兼容旧客户端或代理
- 无需 HTTP/2 高级特性
http2
模块:- 高并发场景(如 API 服务、实时应用)
- 需要减少延迟(多路复用)
- 传输大量重复头部(如 Cookies)
- 服务器推送资源(如提前发送 CSS/JS)
3. 代码示例
HTTP/1.1 服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello HTTP/1.1!');
});
server.listen(3000, () => {
console.log('HTTP/1.1 server on port 3000');
});
HTTP/2 服务器(需 TLS)
const http2 = require('http2');
const fs = require('fs');
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
cert: fs.readFileSync('localhost-cert.pem'),
allowHTTP1: true // 允许 HTTP/1.1 降级
});
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello HTTP/2!</h1>');
});
server.listen(3001, () => {
console.log('HTTP/2 server on port 3001');
});
4. 关键注意事项
证书要求:
- HTTP/2 默认需要 TLS,可通过
insecure
选项禁用(仅限开发环境):const server = http2.createServer({ insecure: true });
- HTTP/2 默认需要 TLS,可通过
客户端兼容性:
- 使用
http2.connect()
连接 HTTP/2 服务器:const client = http2.connect('https://localhost:3001'); const req = client.request({ ':path': '/' }); req.on('response', (headers) => { // 处理响应 });
- 使用
性能优化:
- 启用
settings
配置优化流控:server.on('session', (session) => { session.settings({ enablePush: true, initialWindowSize: 65535 }); });
- 启用
5. 迁移建议
渐进式迁移:
- 使用
allowHTTP1: true
让服务器同时支持 HTTP/1.1 和 HTTP/2。 - 通过
ALPN
协议自动协商版本。
- 使用
工具链支持:
- 使用
curl --http2
或 Postman 测试 HTTP/2。 - 监控工具:Wireshark 或
nghttp2 -v
。
- 使用
官方文档
如果需要更具体的场景实现(如双向流、动态推送),请提供详细需求!