一、Express框架核心概念
-
框架定位
Express是基于Node.js平台的极简Web开发框架,封装了原生
http
模块,简化了Web服务器开发流程12。 -
核心功能
- 路由系统:通过HTTP方法(GET、POST等)和路径匹配请求
- 中间件:可插拔的请求处理模块
- 静态资源托管:快速搭建文件服务34
二、环境搭建与基础使用
1. 安装Node.js与Express
csharp
# 安装Node.js(官网下载)
node -v # 验证安装
# 初始化项目并安装Express
npm init -y
npm install express
2. 创建基础服务器
javascript
// app.js
const express = require('express');
const app = express();
const port = 3000;
// 定义根路由
app.get('/', (req, res) => {
res.send('Hello Express!');
});
// 启动服务
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
运行命令:node app.js
,访问http://localhost:3000
即可看到响应12。
三、路由系统详解
1. 基础路由定义
javascript
// GET请求处理
app.get('/api/user', (req, res) => {
res.json({ name: 'John', age: 30 });
});
// POST请求处理
app.post('/api/login', (req, res) => {
res.send('Login Success');
});
2. 动态路由参数
javascript
app.get('/product/:id', (req, res) => {
const productId = req.params.id;
res.send(`Product ID: ${productId}`);
});
3. 路由模块化(推荐)
创建routes/user.js
:
ini
const router = express.Router();
router.get('/list', (req, res) => {
res.send('User List');
});
module.exports = router;
主文件中挂载:
ini
const userRouter = require('./routes/user');
app.use('/user', userRouter);
四、中间件实践
1. 常用内置中间件
php
// 解析JSON请求体
app.use(express.json());
// 解析表单数据
app.use(express.urlencoded({ extended: true }));
// 托管静态文件
app.use(express.static('public'));
2. 自定义中间件
javascript
// 日志中间件
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // 传递给下一个中间件
});
// 错误处理中间件
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Server Error');
});
五、完整示例项目
文件结构
arduino
project/
├── app.js
├── routes/
│ └── user.js
└── public/
└── index.html
代码实现
javascript
// app.js
const express = require('express');
const app = express();
// 中间件
app.use(express.json());
app.use(express.static('public'));
// 路由
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// 用户模块路由
const userRouter = require('./routes/user');
app.use('/api/users', userRouter);
// 启动服务
app.listen(3000, () => {
console.log('Server started on port 3000');
});