[ PROMPT_NODE_25006 ]
Resources 实施手册
[ SKILL_DOCUMENTATION ]
# Node.js 后端模式实现手册
此文件包含该技能引用的详细模式、检查清单和代码示例。
# Node.js 后端模式
为构建可扩展、可维护且生产就绪的 Node.js 后端应用程序提供全面指导,涵盖现代框架、架构模式和最佳实践。
## 何时使用此技能
- 构建 REST API 或 GraphQL 服务器
- 创建微服务
- 实现身份验证和授权
- 设计可扩展的后端架构
- 设置中间件和错误处理
- 集成数据库(SQL 和 NoSQL)
- 使用 WebSocket 构建实时应用程序
- 实现后台作业处理
## 核心框架
### Express.js - 极简框架
**基本设置:**
typescript
import express, { Request, Response, NextFunction } from 'express';
import helmet from 'helmet';
import cors from 'cors';
import compression from 'compression';
const app = express();
// 安全中间件
app.use(helmet());
app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(',') }));
app.use(compression());
// 请求体解析
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// 请求日志
app.use((req: Request, res: Response, next: NextFunction) => {
console.log(`${req.method} ${req.path}`);
next();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器运行在端口 ${PORT}`);
});
### Fastify - 高性能框架
**基本设置:**
typescript
import Fastify from 'fastify';
import helmet from '@fastify/helmet';
import cors from '@fastify/cors';
import compress from '@fastify/compress';
const fastify = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
transport: {
target: 'pino-pretty',
options: { colorize: true }
}
}
});
// 插件
await fastify.register(helmet);
await fastify.register(cors, { origin: true });
await fastify.register(compress);
// 带有模式验证的类型安全路由
fastify.post('/users', {
schema: {
body: {
type: 'object',
required: ['name', 'email'],
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' }
}
}
}
}, async (request, reply) => {
const { name, email } = request.body;
return { id: '"