Vue:后端服务代码解析
原代码:
const express = require('express');
const mysql = require('mysql2/promise'); // 使用promise版本
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json()); // 解析JSON请求体
// 数据库连接池
const pool = mysql.createPool({
host: 'localhost',
port: 3306,
user: 'root',
password: '123456',
database: 'admin_system',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// 管理员数据API
app.get('/api/administrators', async (req, res) => {
try {
const [rows] = await pool.query(`
SELECT id, admin_name, login_time, status
FROM administrators
ORDER BY login_time DESC
`);
res.json(rows);
} catch (error) {
console.error('数据库查询错误:', error);
res.status(500).json({ error: '数据库查询失败' });
}
});
// 创建管理员API
app.post('/api/administrators', async (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: '角色类型不能为空' });
}
try {
const [result] = await pool.query(
`INSERT INTO administrators (admin_name, login_time)
VALUES (?, NOW())`,
[name]
);
res.json({
id: result.insertId,
message: '创建成功'
});
} catch (error) {
console.error('创建管理员失败:', error);
res.status(500).json({ error: '创建失败' });
}
});
// 删除管理员API
app.delete('/api/administrators/:id', async (req, res) => {
const id = req.params.id;
try {
const [result] = await pool.query(
`DELETE FROM administrators WHERE id = ?`,
[id]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: '未找到该管理员' });
}
res.json({ message: '删除成功' });
} catch (error) {
console.error('删除管理员失败:', error);
res.status(500).json({ error: '删除失败' });
}
});
// 更新管理员API
app.put('/api/administrators/:id', async (req, res) => {
const id = req.params.id;
const { name, status } = req.body;
try {
const [result] = await pool.query(
`UPDATE administrators
SET admin_name = ?, status = ?, login_time = NOW()
WHERE id = ?`,
[name, status, id]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: '未找到该管理员' });
}
res.json({ message: '更新成功' });
} catch (error) {
console.error('更新管理员失败:', error);
res.status(500).json({ error: '更新失败' });
}
});
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
console.log(`后端服务运行在 http://localhost:${PORT}`);
});
详细代码解析
1. 模块引入
const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
解释:
-
express: Node.js web框架,用于创建服务器和路由 -
mysql2/promise: MySQL数据库的Promise封装版,支持async/await -
cors: 跨域资源共享中间件,解决前端跨域问题
2. Express应用初始化
const app = express();
app.use(cors());
app.use(express.json());
解释:
-
创建Express应用实例
-
app.use(cors()): 启用CORS中间件,允许所有跨域请求 -
app.use(express.json()): 启用JSON请求体解析中间件
3. 数据库连接池配置
const pool = mysql.createPool({
host: 'localhost', // 数据库主机
port: 3306, // 数据库端口
user: 'root', // 数据库用户名
password: '123456', // 数据库密码
database: 'admin_system', // 使用的数据库
waitForConnections: true, // 等待连接
connectionLimit: 10, // 连接池最大连接数
queueLimit: 0 // 排队请求数量限制(0表示不限制)
});
解释:
-
创建MySQL连接池以提高性能
-
connectionLimit: 10: 最大10个并发连接 -
waitForConnections: true: 连接池满时排队等待 -
queueLimit: 0: 等待队列无限长
4. 管理员数据API (GET)
app.get('/api/administrators', async (req, res) => {
try {
// 执行SQL查询,从administrators表中选择id, admin_name, login_time, status,并按登录时间降序排列
const [rows] = await pool.query(`
SELECT id, admin_name, login_time, status
FROM administrators
ORDER BY login_time DESC
`);
// 将查询结果以JSON格式返回
res.json(rows);
} catch (error) {
console.error('数据库查询错误:', error);
res.status(500).json({ error: '数据库查询失败' });
}
});
解释:
-
GET请求端点
/api/administrators -
查询管理员表并按登录时间倒序排列
-
成功返回JSON数据,失败返回500错误
5. 创建管理员API (POST)
app.post('/api/administrators', async (req, res) => {
const { name } = req.body; // 从请求体中获取name
if (!name) {
return res.status(400).json({ error: '角色类型不能为空' });
}
try {
// 执行插入操作,将新管理员的名字和当前时间插入数据库
const [result] = await pool.query(
`INSERT INTO administrators (admin_name, login_time)
VALUES (?, NOW())`,
[name]
);
// 返回新创建的管理员ID和成功消息
res.json({
id: result.insertId,
message: '创建成功'
});
} catch (error) {
console.error('创建管理员失败:', error);
res.status(500).json({ error: '创建失败' });
}
});
解释:
-
POST请求端点,创建新管理员
-
验证请求体中
name参数必填 -
使用
NOW()函数自动设置当前时间 -
返回新创建的管理员ID
6. 删除管理员API (DELETE)
app.delete('/api/administrators/:id', async (req, res) => {
const id = req.params.id; // 从URL参数中获取要删除的管理员ID
try {
// 根据ID删除管理员
const [result] = await pool.query(
`DELETE FROM administrators WHERE id = ?`,
[id]
);
// 如果影响行数为0,表示没有找到该记录
if (result.affectedRows === 0) {
return res.status(404).json({ error: '未找到该管理员' });
}
res.json({ message: '删除成功' });
} catch (error) {
console.error('删除管理员失败:', error);
res.status(500).json({ error: '删除失败' });
}
});
解释:
-
DELETE请求端点,使用URL参数
:id -
检查
affectedRows确认记录是否存在 -
不存在返回404,存在返回成功消息
7. 更新管理员API (PUT)
app.put('/api/administrators/:id', async (req, res) => {
const id = req.params.id;
const { name, status } = req.body;
try {
const [result] = await pool.query(
`UPDATE administrators
SET admin_name = ?, status = ?, login_time = NOW()
WHERE id = ?`,
[name, status, id]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: '未找到该管理员' });
}
res.json({ message: '更新成功' });
} catch (error) {
console.error('更新管理员失败:', error);
res.status(500).json({ error: '更新失败' });
}
});
解释:
-
PUT请求端点,更新管理员信息
-
同时更新
admin_name、status和login_time -
使用
NOW()重置登录时间为当前时间
8. 服务器启动
const PORT = 3000;
app.listen(PORT, () => {
console.log(`后端服务运行在 http://localhost:${PORT}`);
});
解释:
-
监听3000端口启动服务器
-
启动后输出运行地址到控制台
主要特点总结
-
RESTful API设计:符合标准的GET/POST/PUT/DELETE方法
-
安全防护:
-
SQL参数化查询防止注入攻击
-
完善的错误处理和状态码返回
-
-
性能优化:
-
使用数据库连接池管理连接
-
Promise异步处理避免阻塞
-
-
健壮性:
-
所有操作都有try-catch错误处理
-
严格的输入验证
-
资源存在性检查
-
更多推荐


所有评论(0)