// 测试脚本:用于测试服务项目 CRUD 接口 // Node.js 18+ 内置了 fetch,无需额外包 const BASE_URL = 'http://localhost:8090/api' const ADMIN_BASE = 'http://localhost:8090/api/admin' // 获取 Token const TOKEN = 'admin-token' async function test() { console.log('🚀 开始测试服务项目管理 API...') // 1. 测试创建服务(后端) console.log('\n1️⃣ 测试创建新服务("代拿教材")...') try { const res = await fetch(`${ADMIN_BASE}/services`, { method: 'POST', headers: { 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'textbook', // serviceKey: textbook name: '代拿教材', icon: 'help', // 对应前端 icons/help.js baseFee: 5, sort: 100, status: 'active' }) }) const data = await res.json() console.log('创建结果:', JSON.stringify(data, null, 2)) if (data.code === 0) { const newServiceId = data.data.id console.log(`✅ 创建成功!服务 ID: ${newServiceId}`) // 2. 更新服务 console.log('\n2️⃣ 测试更新服务名称...') const updateRes = await fetch(`${ADMIN_BASE}/services/${newServiceId}`, { method: 'PUT', headers: { 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '代取教材(升级版)', baseFee: 6 }) }) const updateData = await updateRes.json() console.log('更新结果:', JSON.stringify(updateData, null, 2)) // 3. 测试前端读取服务列表 console.log('\n3️⃣ 测试前端调用 /api/services...') const frontRes = await fetch(`${BASE_URL}/services`) const frontData = await frontRes.json() console.log('前端服务列表:') frontData.data.forEach(s => { console.log(` - ${s.name} (key=${s.key}, base=${s.base}, icon=${s.icon})`) }) // 4. 重新排序测试 console.log('\n4️⃣ 测试服务排序...') const allServices = frontData.data if (allServices.length >= 2) { const reorderIds = [allServices[1].id, allServices[0].id] // 交换前两个 const reorderRes = await fetch(`${ADMIN_BASE}/services/reorder`, { method: 'PUT', headers: { 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: reorderIds }) }) const reorderData = await reorderRes.json() console.log('排序结果:', JSON.stringify(reorderData, null, 2)) } // 5. 删除服务测试 console.log('\n5️⃣ 测试删除服务(临时创建的 "代取教材")...') const deleteRes = await fetch(`${ADMIN_BASE}/services/${newServiceId}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${TOKEN}` } }) const deleteData = await deleteRes.json() console.log('删除结果:', JSON.stringify(deleteData, null, 2)) console.log('\n✅ 所有测试完成!') } else { console.log('❌ 创建失败:', data.msg) } } catch (e) { console.error('请求错误:', e.message) } } test().catch(console.error)