http https http2
vite里 启动服务使用到了 http https http2
是nodejs里的原生模块
1. HTTP (Hypertext Transfer Protocol)
const http = require('node:http');
// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('HTTP 服务器运行在 http://localhost:3000/');
});
- 无状态协议
- 明文传输
- 默认端口 80
- 每个请求都需要建立新的 TCP 连接
- 不支持服务器推送
2. HTTPS (HTTP Secure)
const https = require('node:https');
const fs = require('node:fs');
// 读取 SSL 证书
const options = {
key: fs.readFileSync('private.key'),
cert: fs.readFileSync('certificate.crt')
};
// 创建 HTTPS 服务器
const server = https.createServer(options, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(443, () => {
console.log('HTTPS 服务器运行在 https://localhost:443/');
});
- 基于 SSL/TLS 加密
- 默认端口 443
- 需要 SSL 证书
- 数据传输加密
- 身份验证
- 数据完整性保护
3. HTTP/2
const http2 = require('node:http2');
const fs = require('node:fs');
// 读取 SSL 证书
const options = {
key: fs.readFileSync('private.key'),
cert: fs.readFileSync('certificate.crt')
};
// 创建 HTTP/2 服务器
const server = http2.createSecureServer(options, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(443, () => {
console.log('HTTP/2 服务器运行在 https://localhost:443/');
});
- 多路复用(一个 TCP 连接可以处理多个请求)
- 服务器推送
- 头部压缩
- 二进制协议
- 默认需要 HTTPS
- 支持流控制
- 支持优先级
在 Vite 中的应用
export async function resolveHttpServer(
{ proxy }: CommonServerOptions,
app: Connect.Server,
httpsOptions?: HttpsServerOptions,
): Promise<HttpServer> {
// 1. 如果没有 HTTPS 配置,使用 HTTP
if (!httpsOptions) {
const { createServer } = await import('node:http')
return createServer(app)
}
// 2. 如果有代理配置,使用 HTTPS
if (proxy) {
const { createServer } = await import('node:https')
return createServer(httpsOptions, app)
}
// 3. 否则使用 HTTP/2
else {
const { createSecureServer } = await import('node:http2')
return createSecureServer(
{
maxSessionMemory: 1000, // 防止大量请求时的 502 错误
...httpsOptions,
allowHTTP1: true, // 允许 HTTP/1.1 回退
},
app,
)
}
}