const http = require('http'); const url = require('url'); const fs = require('fs'); const path = require('path'); const PORT = process.env.PORT || 3000; const server = http.createServer((req, res) => { handleRequest(req, res); }); server.listen(PORT, () => { console.log(`Proxy server is running on port ${PORT}`); }); function handleStaticFile(req, res, path) { const filePath = path.join(__dirname, 'public', path); fs.readFile(filePath, (err, data) => { if (err) { if (err.code === 'ENOENT') { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } else { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error loading the resource'); } } else { // 设置正确的Content-Type const ext = path.extname(filePath); let contentType = 'text/html'; switch (ext) { case '.css': contentType = 'text/css'; break; case '.js': contentType = 'application/javascript'; break; case '.png': contentType = 'image/png'; break; case '.jpg': case '.jpeg': contentType = 'image/jpeg'; break; // 添加其他文件类型的处理 } res.writeHead(200, { 'Content-Type': contentType }); res.end(data); } }); } function proxyApiRequest(req, res, targetUrl) { const options = url.parse(targetUrl); const proxyReq = (options.protocol === 'https:' ? require('https') : http).request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res); }); req.pipe(proxyReq); } function handleRequest(req, res) { const parsedUrl = url.parse(req.url, true); const path = parsedUrl.pathname; // 检查是否为静态文件请求 if (path.startsWith('/static/')) { handleStaticFile(req, res, path.substring('/static/'.length)); } else { // API请求代理 const targetUrl = 'http://api.example.com' + path; // 替换为目标API地址 proxyApiRequest(req, res, targetUrl); } }