Node.js 实战项目:构建 RESTful API
一、项目架构设计与环境搭建
1.1 初始化Node.js项目
我们使用Node.js 18 LTS版本作为开发环境,配合npm 9+进行包管理。通过以下命令初始化项目:
mkdir rest-api && cd rest-api
npm init -y
安装核心依赖:
npm install express@4.18 mongoose@7 jwt-simple@0.5 dotenv@16
npm install --save-dev nodemon@3 eslint@8
项目目录结构建议采用分层架构:
├── config/ # 环境配置
├── controllers/ # 业务逻辑
├── models/ # 数据模型
├── routes/ # 路由定义
├── middlewares/ # 自定义中间件
└── utils/ # 工具函数
1.2 Express框架配置
创建入口文件app.js:
const express = require('express');
const app = express();
// 中间件配置
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 健康检查端点
app.get('/health', (req, res) => {
res.json({ status: 'UP', timestamp: Date.now() });
});
module.exports = app;
在package.json中添加启动脚本:
"scripts": {
"dev": "nodemon app.js",
"start": "node app.js"
}
二、RESTful路由设计与实现
2.1 资源导向架构规范
遵循REST(Representational State Transfer)设计原则,我们以用户资源为例设计端点:
| HTTP方法 | 路径 | 操作 |
|---|---|---|
| GET | /api/v1/users | 获取用户列表 |
| POST | /api/v1/users | 创建新用户 |
| GET | /api/v1/users/:id | 获取单个用户 |
| PUT | /api/v1/users/:id | 更新用户信息 |
| DELETE | /api/v1/users/:id | 删除用户 |
2.2 路由模块化实现
在routes/users.js中定义具体路由:
const router = require('express').Router();
const UserController = require('../controllers/user');
// 获取用户列表(支持分页)
router.get('/', UserController.listUsers);
// 创建新用户(请求体验证中间件)
router.post('/',
validateUserCreate,
UserController.createUser
);
// 导出路由模块
module.exports = router;
三、MongoDB数据库集成
3.1 Mongoose模式定义
创建用户模型models/user.js:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
minlength: 3,
maxlength: 30
},
email: {
type: String,
required: true,
match: /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/
},
password: {
type: String,
required: true,
select: false
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);
3.2 数据库连接优化
在config/database.js中配置连接池:
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 10, // 连接池大小
serverSelectionTimeoutMS: 5000
});
console.log('MongoDB connected');
} catch (err) {
console.error('Database connection failed:', err);
process.exit(1);
}
};
module.exports = connectDB;
四、认证授权与安全防护
4.1 JWT认证实现
创建auth中间件:
const jwt = require('jwt-simple');
const { JWT_SECRET } = process.env;
const authenticate = (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1];
const decoded = jwt.decode(token, JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};
module.exports = { authenticate };
4.2 速率限制与CORS配置
使用express-rate-limit中间件:
const rateLimit = require('express-rate-limit');
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 每个IP限制100次请求
standardHeaders: true,
legacyHeaders: false
});
app.use('/api/', apiLimiter);
五、错误处理与日志记录
5.1 统一错误处理中间件
在app.js最后添加:
app.use((err, req, res, next) => {
console.error(err.stack);
const statusCode = err.statusCode || 500;
const message = statusCode === 500 ?
'Internal Server Error' : err.message;
res.status(statusCode).json({
error: {
code: statusCode,
message: message,
timestamp: new Date().toISOString()
}
});
});
5.2 Winston日志配置
创建logger.js:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({
filename: 'error.log',
level: 'error'
}),
new winston.transports.File({
filename: 'combined.log'
})
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
module.exports = logger;
六、API测试与部署
6.1 Postman测试集合
建议创建包含以下测试用例的集合:
- 成功创建用户(201 Created)
- 重复用户名冲突(409 Conflict)
- 无效邮箱格式验证(400 Bad Request)
- 带分页的用户列表查询(200 OK)
6.2 PM2生产环境部署
配置ecosystem.config.js:
module.exports = {
apps: [{
name: 'rest-api',
script: 'app.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000,
MONGO_URI: 'mongodb+srv://prod-db'
}
}]
};
Node.js, RESTful API, Express框架, MongoDB, JWT认证, 后端开发, API设计, 中间件, Mongoose, 项目实战