const http = require('http'); const https = require('https'); const fs = require('fs'); const path = require('path'); const PORT = 13013; const server = http.createServer((req, res) => { // 1. 处理 API 请求 if (req.url === '/api/chat') { if (req.method === 'OPTIONS') { res.writeHead(200, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS' }); res.end(); return; } if (req.method === 'POST') { const options = { hostname: 'opencode.ai', path: '/zen/v1/chat/completions', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer public', 'User-Agent': 'opencode/1.18.12 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.13', 'x-opencode-client': 'cli' } }; const proxyReq = https.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, { ...proxyRes.headers, 'Access-Control-Allow-Origin': '*' }); proxyRes.pipe(res); }); proxyReq.on('error', (e) => { res.writeHead(500); res.end(JSON.stringify({ error: e.message })); }); req.pipe(proxyReq); } return; } // 2. 托管本地 HTML 页面 (默认加载同目录下的 public.html) const filePath = path.join(__dirname, 'public.html'); fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('未找到 public.html 文件,请确认该文件与 server.js 在同一文件夹下!'); } else { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(data); } }); }); server.listen(PORT, () => { console.log(`服务启动成功!请在浏览器打开地址: http://localhost:${PORT}`); });