import http from 'http' import https from 'https' import { URL } from 'url' const port = 7860 const CORS_HEADERS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Max-Age': '86400' } const server = http.createServer((req, res) => { // 处理预检请求 if (req.method === 'OPTIONS') { res.writeHead(204, { ...CORS_HEADERS, 'Content-Length': '0' }) return res.end() } try { // 解析代理路径 const proxyPath = req.url?.replace(/^\/proxy\//i, '') const targetUrl = new URL(proxyPath) const isHttps = targetUrl.protocol === 'https:' // 构建代理请求选项 const options = { hostname: targetUrl.hostname, port: targetUrl.port || (isHttps ? 443 : 80), path: targetUrl.pathname + targetUrl.search, method: req.method, headers: { ...req.headers } } // 清理请求头 delete options.headers.host delete options.headers.origin delete options.headers.referer // 创建代理请求 const proxy = (isHttps ? https : http).request(options, (proxyRes) => { // 注入CORS头 const responseHeaders = { ...proxyRes.headers, ...CORS_HEADERS } res.writeHead(proxyRes.statusCode || 200, responseHeaders) proxyRes.pipe(res, { end: true }) }) // 错误处理 proxy.on('error', (err) => { console.error(`Proxy error: ${err.message}`) res.writeHead(502, { 'Content-Type': 'text/plain', ...CORS_HEADERS }) res.end('Bad Gateway') }) // 流式传输请求体 req.pipe(proxy, { end: true }) } catch (error) { res.writeHead(400, { 'Content-Type': 'text/plain', ...CORS_HEADERS }) res.end('Invalid proxy URL') } }) // 启动服务器 server.listen(port, () => { console.log(`Proxy server is running on http://localhost:${port}`) })