-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (64 loc) · 2.07 KB
/
Copy pathindex.js
File metadata and controls
73 lines (64 loc) · 2.07 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');
const http = require('http');
const https = require('https');
const app = express();
const port = 8080;
const targetUrl = 'https://lmnet.cf';
//Testing
// Function to check if the target URL is online
function checkTargetOnline(url) {
return new Promise((resolve) => {
const urlObj = new URL(url);
const options = {
method: 'HEAD',
host: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname,
};
const req = (urlObj.protocol === 'https:' ? https : http).request(options, (res) => {
resolve(res.statusCode < 400);
});
req.on('error', () => resolve(false));
req.end();
});
}
// Middleware to log each request
app.use((req, res, next) => {
console.log(`Request URL: ${req.url}`);
next();
});
// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));
// Middleware to check if the target URL is online before proxying
app.use('/', async (req, res, next) => {
const isOnline = await checkTargetOnline(targetUrl);
if (isOnline) {
createProxyMiddleware({
target: targetUrl,
changeOrigin: true,
onProxyReq: (proxyReq, req, res) => {
console.log(`Proxying request to: ${proxyReq.path}`);
},
onProxyRes: (proxyRes, req, res) => {
console.log(`Received response from: ${proxyRes.req.path}`);
},
onError: (err, req, res) => {
console.error(`Error during proxying: ${err.message}`);
res.sendFile(path.join(__dirname, 'public', 'error.html'));
}
})(req, res, next);
} else {
console.error(`${targetUrl} is offline. Serving error page.`);
res.sendFile(path.join(__dirname, 'public', 'error.html'));
}
});
// Fallback route to serve index.html for non-API routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'errr.html'));
});
// Start the server
app.listen(port, () => {
console.log(`Proxy server listening on port ${port}`);
});