express-rest-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Express REST API Skill

Express REST API 实战技能

Master building robust, scalable REST APIs with Express.js, the de-facto standard for Node.js web frameworks.
掌握使用Express.js构建健壮、可扩展的REST API,Express.js是Node.js Web框架的事实标准。

Quick Start

快速开始

Build a basic Express API in 5 steps:
  1. Setup Express -
    npm install express
  2. Create Routes - Define GET, POST, PUT, DELETE endpoints
  3. Add Middleware - JSON parsing, CORS, security headers
  4. Handle Errors - Centralized error handling
  5. Test & Deploy - Use Postman/Insomnia, deploy to cloud
通过5个步骤构建基础的Express API:
  1. 安装Express -
    npm install express
  2. 创建路由 - 定义GET、POST、PUT、DELETE端点
  3. 添加中间件 - JSON解析、CORS、安全头
  4. 错误处理 - 集中式错误处理
  5. 测试与部署 - 使用Postman/Insomnia进行测试,部署到云端

Core Concepts

核心概念

1. Express Application Structure

1. Express应用结构

javascript
const express = require('express');
const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);

// Error handling
app.use(errorHandler);

app.listen(3000, () => console.log('Server running'));
javascript
const express = require('express');
const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);

// Error handling
app.use(errorHandler);

app.listen(3000, () => console.log('Server running'));

2. RESTful Route Design

2. RESTful路由设计

javascript
// GET    /api/users       - Get all users
// GET    /api/users/:id   - Get user by ID
// POST   /api/users       - Create user
// PUT    /api/users/:id   - Update user
// DELETE /api/users/:id   - Delete user

const router = express.Router();

router.get('/', getAllUsers);
router.get('/:id', getUserById);
router.post('/', createUser);
router.put('/:id', updateUser);
router.delete('/:id', deleteUser);

module.exports = router;
javascript
// GET    /api/users       - 获取所有用户
// GET    /api/users/:id   - 根据ID获取用户
// POST   /api/users       - 创建用户
// PUT    /api/users/:id   - 更新用户
// DELETE /api/users/:id   - 删除用户

const router = express.Router();

router.get('/', getAllUsers);
router.get('/:id', getUserById);
router.post('/', createUser);
router.put('/:id', updateUser);
router.delete('/:id', deleteUser);

module.exports = router;

3. Middleware Patterns

3. 中间件模式

javascript
// Authentication middleware
const authenticate = (req, res, next) => {
  const token = req.headers.authorization;
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  // Verify token...
  next();
};

// Validation middleware
const validate = (schema) => (req, res, next) => {
  const { error } = schema.validate(req.body);
  if (error) return res.status(400).json({ error: error.message });
  next();
};

// Usage
router.post('/users', authenticate, validate(userSchema), createUser);
javascript
// 认证中间件
const authenticate = (req, res, next) => {
  const token = req.headers.authorization;
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  // 验证token...
  next();
};

// 验证中间件
const validate = (schema) => (req, res, next) => {
  const { error } = schema.validate(req.body);
  if (error) return res.status(400).json({ error: error.message });
  next();
};

// 使用示例
router.post('/users', authenticate, validate(userSchema), createUser);

4. Error Handling

4. 错误处理

javascript
// Custom error class
class APIError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
  }
}

// Global error handler
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: false,
    error: err.message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});
javascript
// 自定义错误类
class APIError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
  }
}

// 全局错误处理器
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: false,
    error: err.message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});

Learning Path

学习路径

Beginner (2-3 weeks)

入门阶段(2-3周)

  • ✅ Setup Express and create basic routes
  • ✅ Understand middleware concept
  • ✅ Implement CRUD operations
  • ✅ Test with Postman
  • ✅ 搭建Express环境并创建基础路由
  • ✅ 理解中间件概念
  • ✅ 实现CRUD操作
  • ✅ 使用Postman进行测试

Intermediate (4-6 weeks)

中级阶段(4-6周)

  • ✅ Implement authentication (JWT)
  • ✅ Add input validation
  • ✅ Organize code (MVC pattern)
  • ✅ Connect to database
  • ✅ 实现认证功能(JWT)
  • ✅ 添加输入验证
  • ✅ 代码组织(MVC模式)
  • ✅ 连接数据库

Advanced (8-10 weeks)

高级阶段(8-10周)

  • ✅ API versioning (
    /api/v1/
    ,
    /api/v2/
    )
  • ✅ Rate limiting and security
  • ✅ Pagination and filtering
  • ✅ API documentation (Swagger)
  • ✅ Performance optimization
  • ✅ API版本控制(
    /api/v1/
    ,
    /api/v2/
  • ✅ 请求频率限制与安全防护
  • ✅ 分页与过滤
  • ✅ API文档(Swagger)
  • ✅ 性能优化

Essential Packages

必备包

javascript
{
  "dependencies": {
    "express": "^4.18.0",
    "helmet": "^7.0.0",          // Security headers
    "cors": "^2.8.5",            // Cross-origin requests
    "morgan": "^1.10.0",         // HTTP logger
    "express-validator": "^7.0.0", // Input validation
    "express-rate-limit": "^6.0.0" // Rate limiting
  }
}
javascript
{
  "dependencies": {
    "express": "^4.18.0",
    "helmet": "^7.0.0",          // 安全头
    "cors": "^2.8.5",            // 跨域请求
    "morgan": "^1.10.0",         // HTTP日志
    "express-validator": "^7.0.0", // 输入验证
    "express-rate-limit": "^6.0.0" // 请求频率限制
  }
}

Common Patterns

常见模式

Response Format

响应格式

javascript
// Success
{ success: true, data: {...} }

// Error
{ success: false, error: "Message" }

// Pagination
{
  success: true,
  data: [...],
  pagination: { page: 1, limit: 10, total: 100 }
}
javascript
// 成功响应
{ success: true, data: {...} }

// 错误响应
{ success: false, error: "Message" }

// 分页响应
{
  success: true,
  data: [...],
  pagination: { page: 1, limit: 10, total: 100 }
}

HTTP Status Codes

HTTP状态码

  • 200 OK
    - Successful GET/PUT
  • 201 Created
    - Successful POST
  • 204 No Content
    - Successful DELETE
  • 400 Bad Request
    - Validation error
  • 401 Unauthorized
    - Auth required
  • 403 Forbidden
    - No permission
  • 404 Not Found
    - Resource not found
  • 500 Internal Error
    - Server error
  • 200 OK
    - GET/PUT请求成功
  • 201 Created
    - POST请求成功
  • 204 No Content
    - DELETE请求成功
  • 400 Bad Request
    - 验证错误
  • 401 Unauthorized
    - 需要认证
  • 403 Forbidden
    - 无权限
  • 404 Not Found
    - 资源不存在
  • 500 Internal Error
    - 服务器错误

Project Structure

项目结构

src/
├── controllers/    # Route handlers
├── routes/        # Route definitions
├── middlewares/   # Custom middleware
├── models/        # Data models
├── services/      # Business logic
├── utils/         # Helpers
└── app.js         # Express setup
src/
├── controllers/    # 路由处理器
├── routes/        # 路由定义
├── middlewares/   # 自定义中间件
├── models/        # 数据模型
├── services/      # 业务逻辑
├── utils/         # 工具函数
└── app.js         # Express配置文件

Production Checklist

生产环境检查清单

  • ✅ Environment variables (.env)
  • ✅ Security headers (Helmet)
  • ✅ CORS configuration
  • ✅ Rate limiting
  • ✅ Input validation
  • ✅ Error handling
  • ✅ Logging (Morgan/Winston)
  • ✅ Testing (Jest/Supertest)
  • ✅ API documentation
  • ✅ 环境变量(.env)
  • ✅ 安全头(Helmet)
  • ✅ CORS配置
  • ✅ 请求频率限制
  • ✅ 输入验证
  • ✅ 错误处理
  • ✅ 日志记录(Morgan/Winston)
  • ✅ 测试(Jest/Supertest)
  • ✅ API文档

Real-World Example

实战示例

Complete user API:
javascript
const express = require('express');
const router = express.Router();
const { body } = require('express-validator');

// GET /api/users
router.get('/', async (req, res, next) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const users = await User.find()
      .limit(limit)
      .skip((page - 1) * limit);

    res.json({ success: true, data: users });
  } catch (error) {
    next(error);
  }
});

// POST /api/users
router.post('/',
  body('email').isEmail(),
  body('password').isLength({ min: 8 }),
  async (req, res, next) => {
    try {
      const user = await User.create(req.body);
      res.status(201).json({ success: true, data: user });
    } catch (error) {
      next(error);
    }
  }
);

module.exports = router;
完整的用户API:
javascript
const express = require('express');
const router = express.Router();
const { body } = require('express-validator');

// GET /api/users
router.get('/', async (req, res, next) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const users = await User.find()
      .limit(limit)
      .skip((page - 1) * limit);

    res.json({ success: true, data: users });
  } catch (error) {
    next(error);
  }
});

// POST /api/users
router.post('/',
  body('email').isEmail(),
  body('password').isLength({ min: 8 }),
  async (req, res, next) => {
    try {
      const user = await User.create(req.body);
      res.status(201).json({ success: true, data: user });
    } catch (error) {
      next(error);
    }
  }
);

module.exports = router;

When to Use

适用场景

Use Express REST API when:
  • Building backend for web/mobile apps
  • Creating microservices
  • Developing API-first applications
  • Need flexible, lightweight framework
  • Want large ecosystem and community
在以下场景使用Express REST API:
  • 为Web/移动应用构建后端
  • 创建微服务
  • 开发API优先的应用
  • 需要灵活、轻量级的框架
  • 希望使用庞大的生态系统和社区支持

Related Skills

相关技能

  • Async Programming (handle async operations)
  • Database Integration (connect to MongoDB/PostgreSQL)
  • JWT Authentication (secure your APIs)
  • Jest Testing (test your endpoints)
  • Docker Deployment (containerize your API)
  • 异步编程(处理异步操作)
  • 数据库集成(连接MongoDB/PostgreSQL)
  • JWT认证(保护你的API)
  • Jest测试(测试你的端点)
  • Docker部署(容器化你的API)

Resources

资源