cw332's picture
PERFORM THE FOLLOWING OPERATIONS:
3ec47db verified
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}`);
});