-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js.backup.txt
More file actions
57 lines (47 loc) · 1.9 KB
/
proxy.js.backup.txt
File metadata and controls
57 lines (47 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require('dotenv').config({ quiet: true });
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const host = process.env.HOST || '0.0.0.0';
const port = process.env.PORT || 3000;
app.use(async (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
if (req.method === 'OPTIONS') return res.sendStatus(204);
const fullPath = req.originalUrl.slice(1); //req.path.slice(1);
let targetUrl;
try {
targetUrl = decodeURIComponent(fullPath); //fullPath;
} catch {
return res.status(400).send('Invalid URL encoding');
}
console.log('=='+targetUrl+'==');
if (!/^(http|https)?:\/\//i.test(targetUrl)) {
return res.status(400).send('Invalid target URL. *Must start with http:// or https://');
}
const proxy = createProxyMiddleware({
target: targetUrl,
changeOrigin: true,
secure: false,
logLevel: 'silent',
onProxyReq: (proxyReq, req, res) => {
// Example: override Host header manually if needed:
console.log(proxyReq.headers)
console.log(req.headers)
proxyReq.setHeader('Host', new URL(targetUrl).host);
},
onProxyRes(proxyRes, req, res) {
proxyRes.headers['access-control-allow-origin'] = '*';
proxyRes.headers['access-control-allow-methods'] = 'GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD';
proxyRes.headers['access-control-allow-headers'] = 'Content-Type, Authorization, X-Requested-With';
},
onError(err, req, res) {
res.status(500).send('Proxy error: ' + err.message);
}
});
proxy(req, res, next);
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});