Node.js 实战:用 Express 编写简单 API 服务

以下分步骤实现一个具备基础功能的 RESTful API 服务,包含用户管理功能:


1. 环境初始化
mkdir express-api && cd express-api
npm init -y
npm install express body-parser


2. 创建基础服务文件 (app.js)
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3000;

// 中间件配置
app.use(bodyParser.json());

// 模拟数据库
let users = [
  { id: 1, name: '张三', email: 'zhangsan@example.com' },
  { id: 2, name: '李四', email: 'lisi@example.com' }
];

// 根路由
app.get('/', (req, res) => {
  res.send('API 服务已启动');
});

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


3. 实现用户管理 API
(1) 获取所有用户 (GET)
app.get('/api/users', (req, res) => {
  res.json(users);
});

(2) 创建新用户 (POST)
app.post('/api/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

(3) 更新用户 (PUT)
app.put('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const user = users.find(u => u.id === userId);
  
  if (!user) return res.status(404).json({ error: '用户不存在' });
  
  user.name = req.body.name || user.name;
  user.email = req.body.email || user.email;
  
  res.json(user);
});

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


4. 测试 API

使用 curlPostman 测试:

创建用户:

curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"王五", "email":"wangwu@example.com"}'

获取所有用户:

curl http://localhost:3000/api/users

更新用户:

curl -X PUT http://localhost:3000/api/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name":"张老三"}'


5. 完整代码结构
express-api/
├── node_modules/
├── app.js
├── package.json
└── package-lock.json

启动服务:

node app.js


6. 关键概念说明
  1. 路由处理

    • app.get() 处理 GET 请求
    • app.post() 处理 POST 请求
    • :id 是动态路由参数
  2. 中间件

    • body-parser 解析 JSON 请求体
    • 自定义中间件可添加权限验证等
  3. 状态码

    • 200 OK
    • 201 Created
    • 204 No Content
    • 404 Not Found

下一步优化建议
  1. 添加数据库连接 (MongoDB/MySQL)
  2. 实现 JWT 身份验证
  3. 添加请求参数验证
  4. 使用路由分离架构
  5. 增加错误处理中间件

通过此实现,您已掌握 Express 构建 API 的核心模式,可根据需求扩展更多功能模块。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐