Rouder commited on
Commit
060ee91
·
verified ·
1 Parent(s): df67720

Update proxy.js

Browse files
Files changed (1) hide show
  1. proxy.js +38 -7
proxy.js CHANGED
@@ -1,26 +1,57 @@
1
  const express = require('express');
2
  const { createProxyMiddleware } = require('http-proxy-middleware');
 
3
 
4
  const app = express();
5
  const PORT = process.env.PORT || 3000;
6
  const TARGET_URL = process.env.TARGET_URL || 'https://domain.com';
7
 
8
- // 代理所有请求到目标URL
9
- app.use('/', createProxyMiddleware({
 
 
 
 
 
 
 
 
 
 
 
 
10
  target: TARGET_URL,
11
  changeOrigin: true,
12
- logLevel: 'info',
 
 
 
13
  onProxyReq: (proxyReq, req, res) => {
14
- // 可选:添加或修改请求头
15
- proxyReq.setHeader('X-Proxy-Server', 'Node-Proxy');
 
16
  },
17
  onError: (err, req, res) => {
18
  console.error('Proxy error:', err);
19
- res.status(500).send('Proxy error occurred');
 
 
 
 
20
  }
21
- }));
 
 
 
 
 
 
 
 
 
22
 
23
  app.listen(PORT, () => {
24
  console.log(`Proxy server running on http://localhost:${PORT}`);
25
  console.log(`Proxying requests to: ${TARGET_URL}`);
 
26
  });
 
1
  const express = require('express');
2
  const { createProxyMiddleware } = require('http-proxy-middleware');
3
+ const cors = require('cors');
4
 
5
  const app = express();
6
  const PORT = process.env.PORT || 3000;
7
  const TARGET_URL = process.env.TARGET_URL || 'https://domain.com';
8
 
9
+ // 允许所有跨域请求(生产环境应限制来源)
10
+ app.use(cors({
11
+ origin: '*',
12
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
13
+ allowedHeaders: ['Content-Type', 'Authorization']
14
+ }));
15
+
16
+ // 健康检查端点
17
+ app.get('/health', (req, res) => {
18
+ res.status(200).json({ status: 'healthy' });
19
+ });
20
+
21
+ // 代理中间件配置
22
+ const proxyOptions = {
23
  target: TARGET_URL,
24
  changeOrigin: true,
25
+ secure: false, // 仅开发使用,生产环境应为true
26
+ logLevel: 'debug',
27
+ xfwd: true, // 添加x-forwarded头
28
+ proxyTimeout: 10000, // 10秒超时
29
  onProxyReq: (proxyReq, req, res) => {
30
+ // 添加或修改请求头
31
+ proxyReq.setHeader('X-Forwarded-For', req.ip);
32
+ proxyReq.setHeader('X-Proxy-Server', 'Node-Proxy-Service');
33
  },
34
  onError: (err, req, res) => {
35
  console.error('Proxy error:', err);
36
+ res.status(502).json({
37
+ error: 'Bad Gateway',
38
+ message: 'Proxy service temporarily unavailable',
39
+ details: err.message
40
+ });
41
  }
42
+ };
43
+
44
+ // 代理所有请求
45
+ app.use('/', createProxyMiddleware(proxyOptions));
46
+
47
+ // 全局错误处理
48
+ app.use((err, req, res, next) => {
49
+ console.error('Global error:', err);
50
+ res.status(500).json({ error: 'Internal Server Error' });
51
+ });
52
 
53
  app.listen(PORT, () => {
54
  console.log(`Proxy server running on http://localhost:${PORT}`);
55
  console.log(`Proxying requests to: ${TARGET_URL}`);
56
+ console.log('CORS enabled for all origins');
57
  });