File size: 2,177 Bytes
3ec47db |
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 cors = require('cors');
const axios = require('axios');
const cheerio = require('cheerio');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
// Proxy endpoint
app.get('/proxy', async (req, res) => {
try {
const targetUrl = req.query.url;
if (!targetUrl) {
return res.status(400).send('URL parameter is required');
}
// Validate URL
try {
new URL(targetUrl);
} catch (e) {
return res.status(400).send('Invalid URL');
}
// Fetch the target page
const response = await axios.get(targetUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
});
// Process the HTML to rewrite links
const $ = cheerio.load(response.data);
// Rewrite all links to go through our proxy
$('a[href]').each((i, el) => {
const href = $(el).attr('href');
try {
const url = new URL(href, targetUrl);
$(el).attr('href', `/proxy?url=${encodeURIComponent(url.href)}`);
} catch (e) {
// Skip invalid URLs
}
});
// Rewrite all form actions to go through our proxy
$('form[action]').each((i, el) => {
const action = $(el).attr('action');
try {
const url = new URL(action, targetUrl);
$(el).attr('action', `/proxy?url=${encodeURIComponent(url.href)}`);
} catch (e) {
// Skip invalid URLs
}
});
// Send the modified content
res.set('Content-Type', response.headers['content-type']);
res.send($.html());
} catch (error) {
console.error('Proxy error:', error);
res.status(500).send('Error fetching the requested URL');
}
});
// Start server
app.listen(PORT, () => {
console.log(`Proxy server running on port ${PORT}`);
}); |