const http = require('http'); const fs = require('fs'); const path = require('path'); const PORT = 3000; const server = http.createServer((req, res) => { console.log(`${req.method} ${req.url}`); // 设置CORS头 res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); if (req.method === 'OPTIONS') { res.writeHead(200); res.end(); return; } let filePath = req.url === '/' ? '/index.html' : req.url; // 如果是API请求,代理到后端 if (req.url.startsWith('/api')) { const http = require('http'); const options = { hostname: 'localhost', port: 8080, path: req.url, method: req.method, headers: req.headers }; const proxyReq = http.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res); }); req.pipe(proxyReq); return; } // 静态文件服务 const fullPath = path.join(__dirname, 'dist', filePath); fs.readFile(fullPath, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end(`
端口: ${PORT}
请先运行 npm run build 构建项目