You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.9 KiB
60 lines
1.9 KiB
|
1 month ago
|
/**
|
||
|
|
* 开发环境代理服务器
|
||
|
|
* 用于解决跨域问题和统一 API 请求
|
||
|
|
*/
|
||
|
|
|
||
|
|
const express = require('express');
|
||
|
|
const { createProxyMiddleware } = require('http-proxy-middleware');
|
||
|
|
|
||
|
|
const app = express();
|
||
|
|
const PORT = 8080;
|
||
|
|
|
||
|
|
// 目标 API 服务器地址
|
||
|
|
const API_TARGET = process.env.API_TARGET || 'http://localhost:3000';
|
||
|
|
|
||
|
|
// 配置代理
|
||
|
|
app.use(
|
||
|
|
'/api',
|
||
|
|
createProxyMiddleware({
|
||
|
|
target: API_TARGET,
|
||
|
|
changeOrigin: true,
|
||
|
|
pathRewrite: {
|
||
|
|
'^/api': '/api', // 保持路径不变,或者根据需要重写
|
||
|
|
},
|
||
|
|
onProxyReq: (proxyReq, req, res) => {
|
||
|
|
console.log(`[Proxy] ${req.method} ${req.url} → ${API_TARGET}${req.url}`);
|
||
|
|
},
|
||
|
|
onProxyRes: (proxyRes, req, res) => {
|
||
|
|
console.log(`[Proxy] ${req.method} ${req.url} ← ${proxyRes.statusCode}`);
|
||
|
|
},
|
||
|
|
onError: (err, req, res) => {
|
||
|
|
console.error('[Proxy Error]', err.message);
|
||
|
|
res.status(500).json({
|
||
|
|
error: 'Proxy Error',
|
||
|
|
message: err.message,
|
||
|
|
});
|
||
|
|
},
|
||
|
|
})
|
||
|
|
);
|
||
|
|
|
||
|
|
// 健康检查
|
||
|
|
app.get('/health', (req, res) => {
|
||
|
|
res.json({
|
||
|
|
status: 'ok',
|
||
|
|
proxy: API_TARGET,
|
||
|
|
timestamp: new Date().toISOString(),
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
app.listen(PORT, () => {
|
||
|
|
console.log(`
|
||
|
|
╔════════════════════════════════════════════════════════╗
|
||
|
|
║ 🚀 Proxy Server Running ║
|
||
|
|
╠════════════════════════════════════════════════════════╣
|
||
|
|
║ Local: http://localhost:${PORT} ║
|
||
|
|
║ Target: ${API_TARGET.padEnd(40)} ║
|
||
|
|
║ Health: http://localhost:${PORT}/health ║
|
||
|
|
╚════════════════════════════════════════════════════════╝
|
||
|
|
`);
|
||
|
|
});
|