fix: 优化端口
This commit is contained in:
@@ -7,11 +7,37 @@ import path from 'path';
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const backendPort = Number(process.env.BACKEND_PORT) || 8000;
|
||||
const backendBase = `http://127.0.0.1:${backendPort}`;
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(morgan('dev'));
|
||||
|
||||
// 代理 /api 和 /auth 到后端,使前端用相对路径即可(任意 -p/-b 端口都正确)
|
||||
async function proxyToBackend(req: express.Request, res: express.Response): Promise<void> {
|
||||
try {
|
||||
const url = backendBase + req.originalUrl;
|
||||
const headers: Record<string, string> = { ...req.headers as Record<string, string> };
|
||||
delete headers.host;
|
||||
const opts: RequestInit = { method: req.method, headers };
|
||||
if (req.body && ['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
||||
opts.body = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
|
||||
if (!headers['content-type']) headers['content-type'] = 'application/json';
|
||||
}
|
||||
const proxyRes = await fetch(url, opts);
|
||||
res.status(proxyRes.status);
|
||||
proxyRes.headers.forEach((v, k) => res.setHeader(k, v));
|
||||
const body = await proxyRes.text();
|
||||
res.send(body);
|
||||
} catch (e) {
|
||||
res.status(502).json({ error: 'proxy_error', detail: String(e) });
|
||||
}
|
||||
}
|
||||
app.use('/api', proxyToBackend);
|
||||
app.use('/auth', proxyToBackend);
|
||||
app.get('/openapi.json', (req, res) => proxyToBackend(req, res));
|
||||
|
||||
const publicDir = path.join(__dirname, '../public');
|
||||
app.use(express.static(publicDir));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user