文档
Node.js Express — RESTful API 增删改查
目标
使用 Express 框架构建一个完整的用户管理 RESTful API,实现 CRUD 操作,数据存储在内存中。
完整代码
// app.js
const express = require('express');
const app = express();
const port = 3000;
// 中间件:解析 JSON 请求体
app.use(express.json());
// 内存数据存储
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
];
let nextId = 3;
// GET /users — 获取所有用户
app.get('/users', (req, res) => {
res.json({ total: users.length, data: users });
});
// GET /users/:id — 获取单个用户
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// POST /users — 创建用户
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'name and email are required' });
}
const user = { id: nextId++, name, email };
users.push(user);
res.status(201).json(user);
});
// PUT /users/:id — 更新用户
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
const { name, email } = req.body;
if (name) user.name = name;
if (email) user.email = email;
res.json(user);
});
// DELETE /users/:id — 删除用户
app.delete('/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: 'User not found' });
users.splice(index, 1);
res.status(204).send();
});
app.listen(port, () => {
console.log(`API server listening at http://localhost:${port}`);
});
运行步骤
# 1. 初始化项目
npm init -y
npm install express
# 2. 保存上述代码为 app.js
# 3. 启动
node app.js
测试
# 获取所有用户
curl http://localhost:3000/users
# 创建用户
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name":"Charlie","email":"charlie@example.com"}'
# 更新用户
curl -X PUT http://localhost:3000/users/1 \
-H "Content-Type: application/json" \
-d '{"name":"Alice Updated"}'
# 删除用户
curl -X DELETE http://localhost:3000/users/3
预期输出
$ node app.js
API server listening at http://localhost:3000
| 请求 | 响应 |
|---|---|
GET /users |
{"total":2,"data":[{...},{...}]} |
POST /users |
{"id":3,"name":"Charlie","email":"charlie@example.com"} |
PUT /users/1 |
{"id":1,"name":"Alice Updated","email":"alice@example.com"} |
DELETE /users/3 |
204 No Content |
要点说明
express.json()中间件解析请求体 JSON- RESTful 命名规范:资源复数形式(
/users),HTTP 方法表达操作 - 状态码:200 成功、201 创建成功、204 删除成功无内容、400 参数错误、404 不存在