#!/usr/bin/env node /** * 前后端API集成测试脚本 * 验证前端展示网站与后端API的连接状态 */ const axios = require('axios') const API_BASE_URL = 'http://localhost:8080/api/v1' const FRONTEND_URL = 'http://localhost:3000' // 测试配置 const testConfig = { username: 'admin', password: 'admin123' } async function testApiConnection() { console.log('🔍 开始前后端API集成测试...\n') try { // 1. 测试后端健康状态 console.log('1. 测试后端健康状态...') const healthResponse = await axios.get(`${API_BASE_URL}/health`) console.log('✅ 后端健康状态:', healthResponse.data.message) // 2. 测试登录获取token console.log('\n2. 测试用户登录...') const loginResponse = await axios.post(`${API_BASE_URL}/auth/login`, testConfig) if (loginResponse.data.code === 0) { console.log('✅ 登录成功:', loginResponse.data.data.user.username) const token = loginResponse.data.data.token // 3. 测试带认证的API调用 console.log('\n3. 测试带认证的API调用...') const headers = { Authorization: `Bearer ${token}` } // 测试分类列表 const categoriesResponse = await axios.get(`${API_BASE_URL}/categories`, { headers }) console.log('✅ 分类列表获取成功:', categoriesResponse.data.data.categories.length, '个分类') // 测试照片列表 const photosResponse = await axios.get(`${API_BASE_URL}/photos`, { headers }) console.log('✅ 照片列表获取成功:', photosResponse.data.data.total, '张照片') // 4. 测试前端网站访问 console.log('\n4. 测试前端网站访问...') try { const frontendResponse = await axios.get(FRONTEND_URL, { timeout: 5000 }) if (frontendResponse.status === 200) { console.log('✅ 前端网站访问成功') } } catch (error) { console.log('⚠️ 前端网站访问失败:', error.message) } // 5. 总结测试结果 console.log('\n🎉 API集成测试完成!') console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━') console.log('🔗 服务状态:') console.log(` 后端API: ${API_BASE_URL} ✅`) console.log(` 前端网站: ${FRONTEND_URL} ✅`) console.log(` 认证功能: ✅ (用户: ${testConfig.username})`) console.log(` 数据接口: ✅ (分类: ${categoriesResponse.data.data.categories.length}个, 照片: ${photosResponse.data.data.total}张)`) console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━') } else { console.log('❌ 登录失败:', loginResponse.data.message) } } catch (error) { console.error('❌ 测试失败:', error.message) if (error.response) { console.error('响应数据:', error.response.data) } } } // 运行测试 testApiConnection()