Express 框架
Express 是基于 Node.js 平台的极简 Web 应用框架,最小化封装,核心代码仅约 1800 行
与传统HTTP模块对比
特性 | 原生HTTP模块 | Express |
---|---|---|
路由管理 | 手动解析URL | 声明式路由系统 |
请求处理 | 单一回调函数 | 中间件链式处理 |
头部处理 | 手动设置 | 便捷方法 |
扩展性 | 需要自行封装 | 中间件生态系统 |
开发效率 | 较低 | 高效 |
路由
// 基础路由示例
app.get('/users/:id', (req, res) => {const userId = req.params.idres.send(`用户ID: ${userId}`)
})// RESTful API 设计
app.route('/articles').get(getArticles).post(createArticle).put(updateArticle).delete(deleteArticle)
基础
const express = require('express')
const app = express()
const port = 3000// 中间件配置
app.use(express.json())
app.use(express.urlencoded({ extended: true }))// 路由定义
app.get('/', (req, res) => {res.json({ status: '服务运行正常', timestamp: new Date() })
})// 错误处理中间件
app.use((err, req, res, next) => {console.error(err.stack)res.status(500).send('服务器错误!')
})// 启动服务
app.listen(port, () => {console.log(`服务运行在 http://localhost:${port}`)
})
常用中间件
中间件名称 | 功能描述 | 安装命令 |
---|---|---|
morgan | HTTP请求日志记录 |
|
helmet | 安全头部设置 |
|
cors | 跨域资源共享支持 |
|
express-session | 会话管理 |
|
passport | 身份认证 |
|
性能优化:
优化方向 | 实现方案 | 示例配置/代码 |
---|---|---|
中间件优化 | 精简中间件数量 | 移除不必要的中间件 |
路由缓存 | 使用路由缓存中间件 |
|
集群模式 | 使用cluster模块 |
|
静态资源 | 使用CDN加速 |
|
数据库连接 | 使用连接池 |
|