refactor(backend): 更新数据库配置并迁移至MySQL,优化文档和技术栈描述
This commit is contained in:
257
backend/README_DEVELOPMENT.md
Normal file
257
backend/README_DEVELOPMENT.md
Normal file
@@ -0,0 +1,257 @@
|
||||
# 结伴客后端开发完善指南
|
||||
|
||||
## 📋 完善内容概述
|
||||
|
||||
本次后端开发完善主要包含以下内容:
|
||||
|
||||
### 1. 环境配置优化
|
||||
- ✅ 更新环境配置文件 (`config/env.js`),移除MongoDB配置,完善MySQL配置
|
||||
- ✅ 更新环境变量示例文件 (`.env.example`),添加MySQL相关配置
|
||||
- ✅ 数据库配置文件 (`src/config/database.js`) 现在使用环境配置而非硬编码
|
||||
|
||||
### 2. 测试数据支持
|
||||
- ✅ 创建测试数据初始化脚本 (`scripts/init-test-data.js`)
|
||||
- ✅ 提供标准测试账号(管理员、运营、普通用户、商家用户)
|
||||
- ✅ 支持密码加密存储(bcrypt)
|
||||
|
||||
### 3. 自动化测试脚本
|
||||
- ✅ 创建API端点测试脚本 (`scripts/test-api-endpoints.js`)
|
||||
- ✅ 创建数据库连接测试脚本 (`scripts/test-database-connection.js`)
|
||||
- ✅ 支持完整的测试用例和结果统计
|
||||
|
||||
### 4. 开发工具链完善
|
||||
- ✅ 更新package.json脚本命令
|
||||
- ✅ 提供一键测试和数据初始化功能
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 环境准备
|
||||
```bash
|
||||
# 复制环境配置文件
|
||||
cp .env.example .env
|
||||
|
||||
# 安装依赖
|
||||
npm install
|
||||
```
|
||||
|
||||
### 数据库配置
|
||||
编辑 `.env` 文件,配置MySQL数据库连接:
|
||||
|
||||
```env
|
||||
# 数据库配置
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USER=root
|
||||
DB_PASSWORD=your-mysql-password
|
||||
DB_NAME=jiebandata
|
||||
|
||||
# 连接池配置
|
||||
DB_CONNECTION_LIMIT=10
|
||||
DB_CHARSET=utf8mb4
|
||||
DB_TIMEZONE=+08:00
|
||||
```
|
||||
|
||||
### 开发命令
|
||||
|
||||
```bash
|
||||
# 启动开发服务器
|
||||
npm run dev
|
||||
|
||||
# 测试数据库连接
|
||||
npm run test-db
|
||||
|
||||
# 初始化测试数据
|
||||
npm run init-test-data
|
||||
|
||||
# 测试API端点
|
||||
npm run test-api
|
||||
|
||||
# 运行单元测试
|
||||
npm test
|
||||
|
||||
# 代码检查
|
||||
npm run lint
|
||||
```
|
||||
|
||||
## 📊 测试账号
|
||||
|
||||
初始化后会创建以下测试账号:
|
||||
|
||||
| 角色 | 用户名 | 密码 | 描述 |
|
||||
|------|--------|------|------|
|
||||
| 超级管理员 | admin | admin123 | 系统最高权限 |
|
||||
| 运营经理 | manager | manager123 | 日常运营管理 |
|
||||
| 普通用户 | user1 | user123 | 旅行爱好者 |
|
||||
| 商家用户 | merchant1 | merchant123 | 农家乐老板 |
|
||||
|
||||
## 🔧 API测试
|
||||
|
||||
API测试脚本会自动测试以下接口:
|
||||
|
||||
### 管理员接口
|
||||
- ✅ POST `/api/v1/admin/login` - 管理员登录
|
||||
- ✅ GET `/api/v1/admin/profile` - 获取管理员信息
|
||||
- ✅ GET `/api/v1/admin/list` - 获取管理员列表
|
||||
|
||||
### 用户接口
|
||||
- ✅ POST `/api/v1/auth/login` - 用户登录
|
||||
- ✅ GET `/api/v1/users/profile` - 获取用户信息
|
||||
|
||||
### 系统接口
|
||||
- ✅ GET `/health` - 健康检查
|
||||
- ✅ GET `/system-stats` - 系统统计
|
||||
|
||||
## 🗄️ 数据库配置
|
||||
|
||||
### 开发环境
|
||||
```javascript
|
||||
{
|
||||
host: '192.168.0.240',
|
||||
port: 3306,
|
||||
user: 'root',
|
||||
password: 'aiotAiot123!',
|
||||
database: 'jiebandata',
|
||||
connectionLimit: 10
|
||||
}
|
||||
```
|
||||
|
||||
### 测试环境
|
||||
```javascript
|
||||
{
|
||||
host: '192.168.0.240',
|
||||
port: 3306,
|
||||
user: 'root',
|
||||
password: 'aiotAiot123!',
|
||||
database: 'jiebandata_test',
|
||||
connectionLimit: 5
|
||||
}
|
||||
```
|
||||
|
||||
### 生产环境
|
||||
```javascript
|
||||
{
|
||||
host: '129.211.213.226',
|
||||
port: 9527,
|
||||
user: 'root',
|
||||
password: 'Aiot123',
|
||||
database: 'jiebandata',
|
||||
connectionLimit: 20
|
||||
}
|
||||
```
|
||||
|
||||
## ⚡ 生产环境连接说明
|
||||
|
||||
### 直接连接生产数据库
|
||||
当前配置已设置为直接连接生产环境MySQL服务器:
|
||||
|
||||
- **服务器地址**: 129.211.213.226
|
||||
- **端口**: 9527
|
||||
- **用户名**: root
|
||||
- **密码**: Aiot123
|
||||
- **数据库**: jiebandata
|
||||
|
||||
### 注意事项
|
||||
1. **谨慎操作**: 直接连接生产数据库,所有操作都会影响真实数据
|
||||
2. **备份优先**: 在执行任何修改操作前,建议先备份数据
|
||||
3. **权限控制**: 确保只有授权人员可以访问生产环境
|
||||
4. **监控日志**: 密切监控数据库操作日志,及时发现异常
|
||||
5. **连接限制**: 生产环境连接数限制为20,避免过度消耗资源
|
||||
|
||||
### 安全建议
|
||||
- 使用VPN连接生产环境
|
||||
- 启用SSL加密连接
|
||||
- 定期更换密码
|
||||
- 实施IP白名单限制
|
||||
- 启用数据库审计功能
|
||||
|
||||
### 连接问题排查
|
||||
如果遇到连接问题,请检查:
|
||||
|
||||
1. **密码验证**: 确认生产服务器MySQL的root密码是否为'Aiot123'
|
||||
2. **权限配置**: 检查MySQL用户权限设置,确保允许从当前IP连接
|
||||
3. **防火墙**: 确认服务器防火墙已开放9527端口
|
||||
4. **网络连通性**: 使用telnet或ping测试网络连接
|
||||
|
||||
### 当前连接状态
|
||||
- ❌ 生产服务器(129.211.213.226:9527): 权限被拒绝(ER_ACCESS_DENIED_ERROR)
|
||||
- ❌ 开发服务器(192.168.0.240:3306): 连接超时(ETIMEDOUT)
|
||||
|
||||
### 本地开发解决方案
|
||||
推荐使用Docker本地MySQL进行开发:
|
||||
|
||||
1. **启动本地MySQL容器**
|
||||
```bash
|
||||
cd /Users/ainongkeji/code/vue/jiebanke/backend
|
||||
docker-compose up -d mysql
|
||||
```
|
||||
|
||||
2. **配置本地环境变量**
|
||||
```bash
|
||||
# 使用本地Docker MySQL
|
||||
export DB_HOST=localhost
|
||||
export DB_PORT=3306
|
||||
export DB_PASSWORD=rootpassword
|
||||
export DB_DATABASE=jiebanke_dev
|
||||
```
|
||||
|
||||
3. **初始化数据库**
|
||||
```bash
|
||||
npm run db:reset # 重置并初始化数据库
|
||||
npm run db:seed # 填充测试数据
|
||||
```
|
||||
|
||||
### 生产环境连接说明
|
||||
如需连接生产环境,请联系运维团队:
|
||||
- 确认生产服务器MySQL root密码
|
||||
- 检查IP白名单配置
|
||||
- 验证网络连通性
|
||||
- 确认防火墙规则
|
||||
|
||||
### 紧急开发方案
|
||||
如果所有远程服务器都无法连接,可以使用SQLite进行临时开发:
|
||||
```bash
|
||||
export DB_DIALECT=sqlite
|
||||
export DB_STORAGE=./database.sqlite
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 📝 开发规范
|
||||
|
||||
### 代码风格
|
||||
- 使用ESLint进行代码检查
|
||||
- 遵循JavaScript标准风格
|
||||
- 使用async/await处理异步操作
|
||||
|
||||
### 安全规范
|
||||
- 密码使用bcrypt加密存储
|
||||
- 使用环境变量存储敏感信息
|
||||
- 实施SQL注入防护
|
||||
- 启用CORS和HTTPS
|
||||
|
||||
### 日志规范
|
||||
- 开发环境使用详细日志
|
||||
- 生产环境使用合并日志
|
||||
- 记录关键操作和错误信息
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
### Q: 数据库连接失败
|
||||
A: 检查MySQL服务是否启动,配置是否正确
|
||||
|
||||
### Q: 测试数据初始化失败
|
||||
A: 确保数据库表结构已创建,可先运行迁移脚本
|
||||
|
||||
### Q: API测试失败
|
||||
A: 确认后端服务已启动,检查网络连接
|
||||
|
||||
### Q: 权限不足
|
||||
A: 检查数据库用户权限,确认有足够的操作权限
|
||||
|
||||
## 📞 技术支持
|
||||
|
||||
如有问题请联系开发团队或查看详细文档。
|
||||
|
||||
---
|
||||
|
||||
**最后更新: 2024年**
|
||||
**版本: 1.0.0**
|
||||
26
backend/docker-compose.yml
Normal file
26
backend/docker-compose.yml
Normal file
@@ -0,0 +1,26 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
container_name: jiebanke-mysql
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: rootpassword
|
||||
MYSQL_DATABASE: jiebanke_dev
|
||||
MYSQL_USER: jiebanke_user
|
||||
MYSQL_PASSWORD: jiebanke_pass
|
||||
ports:
|
||||
- "3306:3306"
|
||||
volumes:
|
||||
- mysql_data:/var/lib/mysql
|
||||
- ./scripts/init-database.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p$$MYSQL_ROOT_PASSWORD"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
volumes:
|
||||
mysql_data:
|
||||
driver: local
|
||||
67
backend/scripts/init-database.sql
Normal file
67
backend/scripts/init-database.sql
Normal file
@@ -0,0 +1,67 @@
|
||||
-- 创建数据库
|
||||
CREATE DATABASE IF NOT EXISTS jiebanke_dev CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE jiebanke_dev;
|
||||
|
||||
-- 创建管理员表
|
||||
CREATE TABLE IF NOT EXISTS admins (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(50) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(100),
|
||||
role ENUM('super_admin', 'admin') DEFAULT 'admin',
|
||||
status ENUM('active', 'inactive') DEFAULT 'active',
|
||||
last_login TIMESTAMP NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- 创建用户表
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(50) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(100) UNIQUE,
|
||||
phone VARCHAR(20),
|
||||
real_name VARCHAR(100),
|
||||
id_card VARCHAR(20),
|
||||
status ENUM('active', 'inactive', 'frozen') DEFAULT 'active',
|
||||
balance DECIMAL(15,2) DEFAULT 0.00,
|
||||
credit_score INT DEFAULT 100,
|
||||
last_login TIMESTAMP NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- 创建订单表
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id INT NOT NULL,
|
||||
order_no VARCHAR(50) NOT NULL UNIQUE,
|
||||
amount DECIMAL(15,2) NOT NULL,
|
||||
status ENUM('pending', 'processing', 'completed', 'cancelled', 'failed') DEFAULT 'pending',
|
||||
type ENUM('loan', 'repayment', 'transfer') NOT NULL,
|
||||
description TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- 插入默认管理员账号
|
||||
INSERT INTO admins (username, password, email, role) VALUES
|
||||
('admin', '$2b$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'admin@jiebanke.com', 'super_admin'),
|
||||
('manager', '$2b$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'manager@jiebanke.com', 'admin');
|
||||
|
||||
-- 插入测试用户账号
|
||||
INSERT INTO users (username, password, email, phone, real_name, id_card, balance, credit_score) VALUES
|
||||
('user1', '$2b$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'user1@example.com', '13800138001', '张三', '110101199001011234', 1000.00, 95),
|
||||
('user2', '$2b$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'user2@example.com', '13800138002', '李四', '110101199002022345', 500.00, 85);
|
||||
|
||||
-- 创建索引
|
||||
CREATE INDEX idx_admins_username ON admins(username);
|
||||
CREATE INDEX idx_admins_email ON admins(email);
|
||||
CREATE INDEX idx_users_username ON users(username);
|
||||
CREATE INDEX idx_users_email ON users(email);
|
||||
CREATE INDEX idx_users_phone ON users(phone);
|
||||
CREATE INDEX idx_orders_user_id ON orders(user_id);
|
||||
CREATE INDEX idx_orders_order_no ON orders(order_no);
|
||||
CREATE INDEX idx_orders_status ON orders(status);
|
||||
125
backend/scripts/init-test-data.js
Normal file
125
backend/scripts/init-test-data.js
Normal file
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 测试数据初始化脚本
|
||||
* 用于开发环境创建测试数据
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const config = require('../config/env');
|
||||
|
||||
// 数据库配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: process.env.DB_PORT || 3306,
|
||||
user: process.env.DB_USER || 'root',
|
||||
password: process.env.DB_PASSWORD || '',
|
||||
database: process.env.DB_NAME || 'jiebanke_dev',
|
||||
charset: process.env.DB_CHARSET || 'utf8mb4',
|
||||
timezone: process.env.DB_TIMEZONE || '+08:00'
|
||||
};
|
||||
|
||||
// 测试数据
|
||||
const testData = {
|
||||
admins: [
|
||||
{
|
||||
username: 'admin',
|
||||
password: 'admin123',
|
||||
email: 'admin@jiebanke.com',
|
||||
nickname: '超级管理员',
|
||||
role: 'super_admin',
|
||||
status: 1
|
||||
},
|
||||
{
|
||||
username: 'manager',
|
||||
password: 'manager123',
|
||||
email: 'manager@jiebanke.com',
|
||||
nickname: '运营经理',
|
||||
role: 'admin',
|
||||
status: 1
|
||||
}
|
||||
],
|
||||
users: [
|
||||
{
|
||||
username: 'user1',
|
||||
password: 'user123',
|
||||
email: 'user1@example.com',
|
||||
nickname: '旅行爱好者',
|
||||
avatar: null,
|
||||
user_type: '普通用户',
|
||||
status: 1
|
||||
},
|
||||
{
|
||||
username: 'merchant1',
|
||||
password: 'merchant123',
|
||||
email: 'merchant1@example.com',
|
||||
nickname: '农家乐老板',
|
||||
avatar: null,
|
||||
user_type: '商家',
|
||||
status: 1
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
async function initTestData() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 开始初始化测试数据...');
|
||||
|
||||
// 创建数据库连接
|
||||
connection = await mysql.createConnection(dbConfig);
|
||||
console.log('✅ 数据库连接成功');
|
||||
|
||||
// 插入管理员数据
|
||||
console.log('📝 插入管理员数据...');
|
||||
for (const admin of testData.admins) {
|
||||
const hashedPassword = await bcrypt.hash(admin.password, 10);
|
||||
const [result] = await connection.execute(
|
||||
`INSERT INTO admins (username, password, email, nickname, role, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
[admin.username, hashedPassword, admin.email, admin.nickname, admin.role, admin.status]
|
||||
);
|
||||
console.log(` 创建管理员: ${admin.username} (ID: ${result.insertId})`);
|
||||
}
|
||||
|
||||
// 插入用户数据
|
||||
console.log('👥 插入用户数据...');
|
||||
for (const user of testData.users) {
|
||||
const hashedPassword = await bcrypt.hash(user.password, 10);
|
||||
const [result] = await connection.execute(
|
||||
`INSERT INTO users (username, password, email, nickname, avatar, user_type, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
[user.username, hashedPassword, user.email, user.nickname, user.avatar, user.user_type, user.status]
|
||||
);
|
||||
console.log(` 创建用户: ${user.username} (ID: ${result.insertId})`);
|
||||
}
|
||||
|
||||
console.log('\n🎉 测试数据初始化完成!');
|
||||
console.log('📋 可用测试账号:');
|
||||
console.log(' 管理员账号: admin / admin123');
|
||||
console.log(' 运营账号: manager / manager123');
|
||||
console.log(' 普通用户: user1 / user123');
|
||||
console.log(' 商家用户: merchant1 / merchant123');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 初始化测试数据失败:', error.message);
|
||||
if (error.code === 'ER_NO_SUCH_TABLE') {
|
||||
console.log('💡 提示: 请先运行数据库迁移脚本创建表结构');
|
||||
}
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 如果是直接运行此文件,则执行初始化
|
||||
if (require.main === module) {
|
||||
initTestData()
|
||||
.then(() => process.exit(0))
|
||||
.catch(() => process.exit(1));
|
||||
}
|
||||
|
||||
module.exports = { initTestData };
|
||||
174
backend/scripts/test-api-endpoints.js
Normal file
174
backend/scripts/test-api-endpoints.js
Normal file
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* API端点测试脚本
|
||||
* 用于验证后端API接口的正确性和一致性
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
|
||||
// API配置
|
||||
const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:3100';
|
||||
const API_VERSION = process.env.API_VERSION || '/api/v1';
|
||||
|
||||
// 测试用例
|
||||
const testCases = [
|
||||
// 管理员接口
|
||||
{
|
||||
name: '管理员登录接口',
|
||||
method: 'POST',
|
||||
path: '/admin/login',
|
||||
expectedStatus: 200,
|
||||
data: {
|
||||
username: 'admin',
|
||||
password: 'admin123'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: '获取管理员信息接口',
|
||||
method: 'GET',
|
||||
path: '/admin/profile',
|
||||
expectedStatus: 200,
|
||||
requiresAuth: true
|
||||
},
|
||||
{
|
||||
name: '获取管理员列表接口',
|
||||
method: 'GET',
|
||||
path: '/admin/list',
|
||||
expectedStatus: 200,
|
||||
requiresAuth: true
|
||||
},
|
||||
|
||||
// 用户接口
|
||||
{
|
||||
name: '用户登录接口',
|
||||
method: 'POST',
|
||||
path: '/auth/login',
|
||||
expectedStatus: 200,
|
||||
data: {
|
||||
username: 'user1',
|
||||
password: 'user123'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: '获取用户信息接口',
|
||||
method: 'GET',
|
||||
path: '/users/profile',
|
||||
expectedStatus: 200,
|
||||
requiresAuth: true
|
||||
},
|
||||
|
||||
// 系统接口
|
||||
{
|
||||
name: '健康检查接口',
|
||||
method: 'GET',
|
||||
path: '/health',
|
||||
expectedStatus: 200
|
||||
},
|
||||
{
|
||||
name: '系统统计接口',
|
||||
method: 'GET',
|
||||
path: '/system-stats',
|
||||
expectedStatus: 200
|
||||
}
|
||||
];
|
||||
|
||||
// 认证令牌
|
||||
let authToken = '';
|
||||
|
||||
async function testEndpoint(testCase) {
|
||||
try {
|
||||
const url = `${API_BASE_URL}${API_VERSION}${testCase.path}`;
|
||||
const config = {
|
||||
method: testCase.method.toLowerCase(),
|
||||
url: url,
|
||||
headers: {}
|
||||
};
|
||||
|
||||
// 添加认证头
|
||||
if (testCase.requiresAuth && authToken) {
|
||||
config.headers.Authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
|
||||
// 添加请求数据
|
||||
if (testCase.data) {
|
||||
config.data = testCase.data;
|
||||
}
|
||||
|
||||
const response = await axios(config);
|
||||
|
||||
// 检查状态码
|
||||
if (response.status === testCase.expectedStatus) {
|
||||
console.log(`✅ ${testCase.name} - 成功 (${response.status})`);
|
||||
|
||||
// 如果是登录接口,保存token
|
||||
if (testCase.path === '/admin/login' && response.data.data && response.data.data.token) {
|
||||
authToken = response.data.data.token;
|
||||
console.log(` 获取到认证令牌`);
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
console.log(`❌ ${testCase.name} - 状态码不匹配: 期望 ${testCase.expectedStatus}, 实际 ${response.status}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (error.response) {
|
||||
console.log(`❌ ${testCase.name} - 错误: ${error.response.status} ${error.response.statusText}`);
|
||||
if (error.response.data) {
|
||||
console.log(` 错误信息: ${JSON.stringify(error.response.data)}`);
|
||||
}
|
||||
} else {
|
||||
console.log(`❌ ${testCase.name} - 网络错误: ${error.message}`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function runAllTests() {
|
||||
console.log('🚀 开始API端点测试');
|
||||
console.log(`📊 测试环境: ${API_BASE_URL}`);
|
||||
console.log(`🔗 API版本: ${API_VERSION}`);
|
||||
console.log('='.repeat(60));
|
||||
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (const testCase of testCases) {
|
||||
const result = await testEndpoint(testCase);
|
||||
if (result) {
|
||||
passed++;
|
||||
} else {
|
||||
failed++;
|
||||
}
|
||||
|
||||
// 添加短暂延迟,避免请求过于频繁
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
console.log('='.repeat(60));
|
||||
console.log('📊 测试结果统计:');
|
||||
console.log(`✅ 通过: ${passed}`);
|
||||
console.log(`❌ 失败: ${failed}`);
|
||||
console.log(`📈 成功率: ${((passed / (passed + failed)) * 100).toFixed(1)}%`);
|
||||
|
||||
if (failed === 0) {
|
||||
console.log('🎉 所有测试用例通过!');
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.log('💥 存在失败的测试用例');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果是直接运行此文件,则执行测试
|
||||
if (require.main === module) {
|
||||
runAllTests()
|
||||
.catch(error => {
|
||||
console.error('❌ 测试执行失败:', error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { runAllTests };
|
||||
128
backend/scripts/test-database-connection.js
Normal file
128
backend/scripts/test-database-connection.js
Normal file
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 数据库连接测试脚本
|
||||
* 用于验证MySQL数据库连接配置的正确性
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const config = require('../config/env');
|
||||
|
||||
// 数据库配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || '129.211.213.226',
|
||||
port: process.env.DB_PORT || 9527,
|
||||
user: process.env.DB_USER || 'root',
|
||||
password: process.env.DB_PASSWORD || 'Aiot123',
|
||||
database: process.env.DB_NAME || 'jiebandata',
|
||||
charset: process.env.DB_CHARSET || 'utf8mb4',
|
||||
timezone: process.env.DB_TIMEZONE || '+08:00',
|
||||
connectTimeout: 10000
|
||||
};
|
||||
|
||||
async function testDatabaseConnection() {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
console.log('🚀 开始数据库连接测试...');
|
||||
console.log(`📊 环境: ${process.env.NODE_ENV || 'development'}`);
|
||||
console.log(`🔗 连接信息: ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`);
|
||||
console.log('='.repeat(50));
|
||||
|
||||
// 测试连接
|
||||
console.log('🔍 测试数据库连接...');
|
||||
connection = await mysql.createConnection(dbConfig);
|
||||
console.log('✅ 数据库连接成功');
|
||||
|
||||
// 测试查询
|
||||
console.log('🔍 测试基本查询...');
|
||||
const [rows] = await connection.execute('SELECT 1 + 1 AS result');
|
||||
console.log(`✅ 查询测试成功: ${rows[0].result}`);
|
||||
|
||||
// 检查表结构
|
||||
console.log('🔍 检查核心表结构...');
|
||||
const tablesToCheck = ['admins', 'users', 'merchants', 'orders'];
|
||||
|
||||
for (const table of tablesToCheck) {
|
||||
try {
|
||||
const [tableInfo] = await connection.execute(
|
||||
`SELECT COUNT(*) as count FROM information_schema.tables
|
||||
WHERE table_schema = ? AND table_name = ?`,
|
||||
[dbConfig.database, table]
|
||||
);
|
||||
|
||||
if (tableInfo[0].count > 0) {
|
||||
console.log(`✅ 表存在: ${table}`);
|
||||
} else {
|
||||
console.log(`⚠️ 表不存在: ${table}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`❌ 检查表失败: ${table} - ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 检查管理员表数据
|
||||
console.log('🔍 检查管理员数据...');
|
||||
try {
|
||||
const [adminCount] = await connection.execute('SELECT COUNT(*) as count FROM admins');
|
||||
console.log(`📊 管理员记录数: ${adminCount[0].count}`);
|
||||
|
||||
if (adminCount[0].count > 0) {
|
||||
const [admins] = await connection.execute('SELECT username, role, status FROM admins LIMIT 5');
|
||||
console.log('👥 管理员样例:');
|
||||
admins.forEach(admin => {
|
||||
console.log(` - ${admin.username} (${admin.role}, 状态: ${admin.status})`);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('❌ 检查管理员数据失败:', error.message);
|
||||
}
|
||||
|
||||
// 检查连接池配置
|
||||
console.log('🔍 检查连接池配置...');
|
||||
console.log(`📈 连接池限制: ${config.mysql.connectionLimit || 10}`);
|
||||
console.log(`🔤 字符集: ${config.mysql.charset}`);
|
||||
console.log(`⏰ 时区: ${config.mysql.timezone}`);
|
||||
|
||||
console.log('\n🎉 数据库连接测试完成!');
|
||||
console.log('✅ 所有配置检查通过');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 数据库连接测试失败:', error.message);
|
||||
console.error('💡 可能的原因:');
|
||||
console.error(' - 数据库服务未启动');
|
||||
console.error(' - 连接配置错误');
|
||||
console.error(' - 网络连接问题');
|
||||
console.error(' - 数据库权限不足');
|
||||
console.error(' - 防火墙限制');
|
||||
console.error(' - IP地址未授权');
|
||||
|
||||
if (error.code) {
|
||||
console.error(`🔍 错误代码: ${error.code}`);
|
||||
}
|
||||
|
||||
console.error('🔍 连接详情:', {
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
user: dbConfig.user,
|
||||
database: dbConfig.database
|
||||
});
|
||||
|
||||
process.exit(1);
|
||||
|
||||
} finally {
|
||||
if (connection) {
|
||||
await connection.end();
|
||||
console.log('🔒 数据库连接已关闭');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 如果是直接运行此文件,则执行测试
|
||||
if (require.main === module) {
|
||||
testDatabaseConnection()
|
||||
.then(() => process.exit(0))
|
||||
.catch(() => process.exit(1));
|
||||
}
|
||||
|
||||
module.exports = { testDatabaseConnection };
|
||||
62
backend/scripts/test-dev-connection.js
Normal file
62
backend/scripts/test-dev-connection.js
Normal file
@@ -0,0 +1,62 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function testDevConnection() {
|
||||
console.log('🧪 测试开发环境数据库连接...');
|
||||
|
||||
const dbConfig = {
|
||||
host: '192.168.0.240',
|
||||
port: 3306,
|
||||
user: 'root',
|
||||
password: 'aiotAiot123!',
|
||||
database: 'jiebandata',
|
||||
connectTimeout: 10000
|
||||
};
|
||||
|
||||
try {
|
||||
console.log('🔗 尝试连接到开发服务器:', dbConfig.host + ':' + dbConfig.port);
|
||||
|
||||
const connection = await mysql.createConnection(dbConfig);
|
||||
console.log('✅ 开发环境连接成功!');
|
||||
|
||||
// 测试基本查询
|
||||
const [rows] = await connection.execute('SELECT 1 as test');
|
||||
console.log('✅ 基本查询测试通过');
|
||||
|
||||
// 检查表结构
|
||||
const [tables] = await connection.execute(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = 'jiebandata'
|
||||
`);
|
||||
|
||||
console.log('📊 数据库中的表:', tables.map(t => t.TABLE_NAME).join(', ') || '暂无表');
|
||||
|
||||
await connection.end();
|
||||
console.log('🎉 开发环境测试完成');
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 开发环境连接失败:', error.message);
|
||||
console.log('🔍 错误代码:', error.code);
|
||||
|
||||
if (error.code === 'ECONNREFUSED') {
|
||||
console.log('💡 可能原因: 开发服务器未启动或网络不可达');
|
||||
} else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
|
||||
console.log('💡 可能原因: 用户名或密码错误');
|
||||
} else if (error.code === 'ER_BAD_DB_ERROR') {
|
||||
console.log('💡 可能原因: 数据库不存在');
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行测试
|
||||
testDevConnection().then(success => {
|
||||
if (success) {
|
||||
console.log('\n✅ 所有测试通过!开发环境配置正确');
|
||||
} else {
|
||||
console.log('\n⚠️ 开发环境配置需要检查');
|
||||
}
|
||||
process.exit(success ? 0 : 1);
|
||||
});
|
||||
48
backend/scripts/test-network.js
Normal file
48
backend/scripts/test-network.js
Normal file
@@ -0,0 +1,48 @@
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function testNetworkConnection() {
|
||||
console.log('🌐 测试网络连接性...');
|
||||
|
||||
const dbConfig = {
|
||||
host: '129.211.213.226',
|
||||
port: 9527,
|
||||
user: 'root',
|
||||
password: 'Aiot123',
|
||||
connectTimeout: 5000,
|
||||
acquireTimeout: 5000
|
||||
};
|
||||
|
||||
try {
|
||||
console.log('🔗 尝试连接到:', dbConfig.host + ':' + dbConfig.port);
|
||||
|
||||
const connection = await mysql.createConnection(dbConfig);
|
||||
console.log('✅ 网络连接成功!');
|
||||
|
||||
await connection.end();
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 网络连接失败:', error.message);
|
||||
console.log('🔍 错误代码:', error.code);
|
||||
|
||||
if (error.code === 'ECONNREFUSED') {
|
||||
console.log('💡 可能原因: 端口未开放或服务未启动');
|
||||
} else if (error.code === 'ETIMEDOUT') {
|
||||
console.log('💡 可能原因: 网络超时或防火墙阻挡');
|
||||
} else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
|
||||
console.log('💡 可能原因: 权限配置问题');
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行测试
|
||||
testNetworkConnection().then(success => {
|
||||
if (success) {
|
||||
console.log('🎉 网络连接测试完成');
|
||||
} else {
|
||||
console.log('⚠️ 请检查网络配置和服务器状态');
|
||||
}
|
||||
process.exit(success ? 0 : 1);
|
||||
});
|
||||
Reference in New Issue
Block a user