connet
github仓库: github.com/senchalabs/…
vite启动本地服务时用到了
使用的 connect + http
import connect from 'connect'
const middlewares = connect() as Connect.Server
const httpServer = await resolveHttpServer(serverConfig, middlewares, httpsOptions)
export async function resolveHttpServer(
{ proxy }: CommonServerOptions,
app: Connect.Server,
httpsOptions?: HttpsServerOptions,
): Promise<HttpServer> {
if (!httpsOptions) {
const { createServer } = await import('node:http')
return createServer(app)
}
// #484 fallback to http1 when proxy is needed.
if (proxy) {
const { createServer } = await import('node:https')
return createServer(httpsOptions, app)
} else {
const { createSecureServer } = await import('node:http2')
return createSecureServer(
{
// Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
// errors on large numbers of requests
maxSessionMemory: 1000,
...httpsOptions,
allowHTTP1: true,
},
// @ts-expect-error TODO: is this correct?
app,
)
}
}
connet的使用方法
Connect 是一个轻量级的 Node.js Web 应用框架,它提供了一种简单的方式来处理 HTTP 请求。它的主要特点是中间件(middleware)机制。
- 基本用法
const connect = require('connect');
const app = connect();
// 添加中间件
app.use((req, res, next) => {
// 处理请求
next(); // 调用下一个中间件
});
// 启动服务器
app.listen(3000);
- 中间件的特点
- 中间件是按照添加顺序依次执行的
- 每个中间件都可以访问请求对象(req)和响应对象(res)
- 通过调用 next() 函数将控制权传递给下一个中间件
- 如果不调用 next(),请求处理就会在当前中间件终止
- 在 Vite 中的应用: Vite 添加了多个中间件来处理不同的功能:
// 请求计时器中间件
middlewares.use(timeMiddleware(root))
// CORS 中间件
middlewares.use(corsMiddleware(...))
// 代理中间件
middlewares.use(proxyMiddleware(...))
// 静态文件服务中间件
middlewares.use(serveStaticMiddleware(server))
// HTML 回退中间件
middlewares.use(htmlFallbackMiddleware(...))
- 中间件的执行顺序
- 中间件按照添加的顺序依次执行
- 请求计时器
- CORS 处理
- 代理处理
- 静态文件服务
- HTML 回退处理
- 错误处理
- 中间件的优势 模块化:每个中间件负责特定的功能 可组合:可以自由组合不同的中间件 可扩展:可以轻松添加新的中间件 可维护:每个中间件都是独立的,便于维护和测试