// 简单的Node.js测试服务器 // 使用方法:node start-test-server.js const http = require('http'); const fs = require('fs'); const path = require('path'); const { URL } = require('url'); // 后端地址 const BACKEND_HOST = 'localhost'; const BACKEND_PORT = 8080; // 前端目录 const FRONTEND_DIR = path.join(__dirname, 'RuoYi-Vue3', 'dist'); // 创建HTTP服务器 const server = http.createServer((req, res) => { const reqUrl = new URL(req.url, `http://${req.headers.host}`); console.log(`${new Date().toISOString()} ${req.method} ${req.url}`); // API代理 if (reqUrl.pathname.startsWith('/prod-api/')) { proxyRequest(req, res, reqUrl); return; } // 静态文件 let filePath = path.join(FRONTEND_DIR, reqUrl.pathname === '/' ? 'index.html' : reqUrl.pathname); // 如果文件不存在,返回index.html(SPA路由) if (!fs.existsSync(filePath)) { filePath = path.join(FRONTEND_DIR, 'index.html'); } // 读取文件 fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(404); res.end('File not found'); return; } // 设置Content-Type const ext = path.extname(filePath); const contentTypes = { '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' }; res.setHeader('Content-Type', contentTypes[ext] || 'application/octet-stream'); res.writeHead(200); res.end(data); }); }); // 代理请求到后端 function proxyRequest(req, res, reqUrl) { const options = { hostname: BACKEND_HOST, port: BACKEND_PORT, path: req.url, method: req.method, headers: req.headers }; const proxyReq = http.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res); }); proxyReq.on('error', (err) => { console.error('Proxy error:', err); res.writeHead(502); res.end('Bad Gateway'); }); req.pipe(proxyReq); } // 启动服务器 const PORT = 8088; server.listen(PORT, () => { console.log('========================================'); console.log('测试服务器已启动'); console.log('========================================'); console.log(`前端地址: http://localhost:${PORT}`); console.log(`后端地址: http://${BACKEND_HOST}:${BACKEND_PORT}/prod-api`); console.log('========================================'); console.log('请在浏览器中打开: http://localhost:8088'); console.log('========================================'); console.log('按 Ctrl+C 停止服务器'); });