104 lines
3.3 KiB
JavaScript
104 lines
3.3 KiB
JavaScript
/**
|
||
* API连接测试脚本
|
||
* @file test-api-connection.js
|
||
* @description 测试前端API与后端的连接
|
||
*/
|
||
|
||
// 测试API连接
|
||
async function testApiConnection() {
|
||
const API_BASE_URL = 'http://localhost:5351';
|
||
|
||
console.log('🔍 开始测试API连接...');
|
||
console.log(`📡 API地址: ${API_BASE_URL}`);
|
||
|
||
try {
|
||
// 测试健康检查
|
||
console.log('\n1. 测试健康检查接口...');
|
||
const healthResponse = await fetch(`${API_BASE_URL}/health`);
|
||
const healthData = await healthResponse.json();
|
||
console.log('✅ 健康检查:', healthData);
|
||
|
||
// 测试认证接口
|
||
console.log('\n2. 测试认证接口...');
|
||
const authResponse = await fetch(`${API_BASE_URL}/api/auth/login`, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
username: 'admin',
|
||
password: 'admin123'
|
||
})
|
||
});
|
||
|
||
if (authResponse.ok) {
|
||
const authData = await authResponse.json();
|
||
console.log('✅ 认证接口正常');
|
||
console.log('📊 响应数据:', authData);
|
||
|
||
// 如果有token,测试需要认证的接口
|
||
if (authData.data && authData.data.token) {
|
||
const token = authData.data.token;
|
||
console.log('\n3. 测试需要认证的接口...');
|
||
|
||
// 测试获取当前用户信息
|
||
const userResponse = await fetch(`${API_BASE_URL}/api/auth/me`, {
|
||
headers: {
|
||
'Authorization': `Bearer ${token}`,
|
||
'Content-Type': 'application/json',
|
||
}
|
||
});
|
||
|
||
if (userResponse.ok) {
|
||
const userData = await userResponse.json();
|
||
console.log('✅ 获取用户信息成功:', userData);
|
||
} else {
|
||
console.log('❌ 获取用户信息失败:', userResponse.status);
|
||
}
|
||
|
||
// 测试仪表盘接口
|
||
const dashboardResponse = await fetch(`${API_BASE_URL}/api/dashboard`, {
|
||
headers: {
|
||
'Authorization': `Bearer ${token}`,
|
||
'Content-Type': 'application/json',
|
||
}
|
||
});
|
||
|
||
if (dashboardResponse.ok) {
|
||
const dashboardData = await dashboardResponse.json();
|
||
console.log('✅ 仪表盘接口正常:', dashboardData);
|
||
} else {
|
||
console.log('❌ 仪表盘接口失败:', dashboardResponse.status);
|
||
}
|
||
|
||
// 测试用户列表接口
|
||
const usersResponse = await fetch(`${API_BASE_URL}/api/users`, {
|
||
headers: {
|
||
'Authorization': `Bearer ${token}`,
|
||
'Content-Type': 'application/json',
|
||
}
|
||
});
|
||
|
||
if (usersResponse.ok) {
|
||
const usersData = await usersResponse.json();
|
||
console.log('✅ 用户列表接口正常:', usersData);
|
||
} else {
|
||
console.log('❌ 用户列表接口失败:', usersResponse.status);
|
||
}
|
||
}
|
||
} else {
|
||
console.log('❌ 认证接口失败:', authResponse.status);
|
||
const errorData = await authResponse.json();
|
||
console.log('错误信息:', errorData);
|
||
}
|
||
|
||
} catch (error) {
|
||
console.error('❌ API连接测试失败:', error.message);
|
||
console.log('\n💡 请确保后端服务正在运行:');
|
||
console.log(' cd bank-backend && npm start');
|
||
}
|
||
}
|
||
|
||
// 运行测试
|
||
testApiConnection();
|