跳转至

618 Express.js REST API

一句话概述:Express 是 Node.js 最流行的 Web 框架,极简且灵活,海量中间件生态,几乎是 Node.js 后端开发的标配,PayPal、Uber 等大公司都在用。

核心知识点速查表

知识点说明
最新版本Express 5.2.x(2025年底发布)
Node.js要求18+(Express 5)
核心特性路由、中间件、模板引擎
生态数千个 npm 中间件包
适用场景REST API、Web应用、微服务

一、安装与基本使用

mkdir my-api && cd my-api
npm init -y                            # 初始化 Node.js 项目
npm install express                    # 安装 Express
// app.js
import express from 'express';         // 导入 Express(ES模块语法)
const app = express();                 // 创建应用
const PORT = 3000;

app.use(express.json());               // 解析 JSON 请求体(内置中间件)

// GET - 获取所有用户
let users = [
    { id: 1, name: '张三', email: 'zhangsan@example.com' },
    { id: 2, name: '李四', email: 'lisi@example.com' }
];

app.get('/api/users', (req, res) => {  // GET 路由
    const { name } = req.query;        // 获取查询参数 ?name=xxx
    let result = users;
    if (name) {
        result = users.filter(u => u.name.includes(name));  // 过滤
    }
    res.json(result);                  // 返回 JSON
});

// GET - 获取单个用户
app.get('/api/users/:id', (req, res) => {  // :id 是路径参数
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ error: '用户不存在' });
    res.json(user);
});

// POST - 创建用户
app.post('/api/users', (req, res) => {
    const { name, email } = req.body;  // 获取请求体
    if (!name || !email) {
        return res.status(400).json({ error: '缺少必填字段' });
    }
    const user = { id: users.length + 1, name, email };
    users.push(user);
    res.status(201).json(user);        // 201 Created
});

// PUT - 更新用户
app.put('/api/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ error: '用户不存在' });
    Object.assign(user, req.body);     // 合并更新字段
    res.json(user);
});

// DELETE - 删除用户
app.delete('/api/users/:id', (req, res) => {
    users = users.filter(u => u.id !== parseInt(req.params.id));
    res.status(204).send();            // 204 No Content
});

app.listen(PORT, () => console.log(`服务运行在 http://localhost:${PORT}`));

二、中间件

// 白话:中间件 = 请求和响应之间的"关卡",每个请求都要过关
import cors from 'cors';              // npm install cors
import helmet from 'helmet';           // npm install helmet(安全头)
import morgan from 'morgan';           // npm install morgan(日志)

app.use(cors());                       // 允许跨域
app.use(helmet());                     // 添加安全响应头
app.use(morgan('dev'));                // 请求日志

// 自定义中间件:认证检查
const authMiddleware = (req, res, next) => {
    const token = req.headers.authorization;
    if (!token) return res.status(401).json({ error: '未认证' });
    // 验证 token...
    next();                            // 调用 next() 继续下一个中间件/路由
};

app.use('/api/protected', authMiddleware);  // 只对 /api/protected 路径生效

三、路由模块化

// routes/users.js
import { Router } from 'express';
const router = Router();

router.get('/', (req, res) => res.json([]));
router.post('/', (req, res) => res.status(201).json(req.body));

export default router;

// app.js 中使用
import userRoutes from './routes/users.js';
app.use('/api/users', userRoutes);     // 挂载到 /api/users 路径

四、错误处理

// 统一错误处理中间件(必须4个参数)
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(err.status || 500).json({
        error: err.message || '服务器内部错误'
    });
});

// Express 5 支持 async 错误自动捕获
app.get('/data', async (req, res) => {
    const data = await fetchData();    // 如果抛异常,Express 5 自动传给错误处理
    res.json(data);
});

五、常见报错与解决

问题解决
Cannot GET /path检查路由定义是否匹配
CORS 错误npm install cors + app.use(cors())
req.body is undefined确保 app.use(express.json()) 在路由之前
Express 4 async 错误不捕获升级到 Express 5 或手动 try-catch

六、速查表

操作代码
GET 路由app.get('/path', handler)
POST 路由app.post('/path', handler)
路径参数req.params.id
查询参数req.query.key
请求体req.body
JSON 响应res.json(data)
状态码res.status(201).json(data)
中间件app.use(middleware)
路由模块app.use('/prefix', router)

七、同类工具对比

特性ExpressFastifyKoaNestJS
性能良好极高良好良好
生态最大增长中中等
TypeScript手动支持手动原生
学习曲线
适合场景通用高性能API极简企业级

选型建议:通用 Node.js API 选 Express(生态最大);追求性能选 Fastify;企业级架构选 NestJS。


参考资料Express 官网 | GitHub | npm