0

This is my code of Node.js Proxy Server.

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cheerio = require('cheerio');
const cors = require('cors');

const app = express();

const targetDomain = "example.com";

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

// Proxy requests to https://${targetDomain}/ for the root URL
app.use('/', createProxyMiddleware({
    target: `https://${targetDomain}/`,
    changeOrigin: true,
    onProxyRes: (proxyRes, req, res) => {
        try {
            proxyRes.headers['Access-Control-Allow-Origin'] = '*';
            proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, PATCH, DELETE';
            proxyRes.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept';
            
            const contentType = proxyRes.headers['content-type'];

            if (contentType && contentType.includes('text/html')) {
                const chunks = [];

                proxyRes.on('data', (chunk) => {
                    chunks.push(chunk);
                });

                proxyRes.on('end', () => {
                    const html = Buffer.concat(chunks).toString('utf-8');
                    const $ = cheerio.load(html);

                    // Adjust URLs in <a> tags, <script> tags, or any other elements as needed
                    $('a').each((index, element) => {
                        const $element = $(element);
                        const href = $element.attr('href');
                        if (href) {
                            $element.attr('href', href.replace(`https://${targetDomain}/`, '/'));
                        }
                    });

                    // Replace any other URLs in the HTML

                    const modifiedHtml = $.html();
                    res.write(modifiedHtml); // Use res.write() instead of res.send()
                    res.end(); // End the response
                });
            }
        } catch (e) {
            console.log('Error:', e);
            res.sendStatus(500);
        }
    }
}));

// Serve assets from https://${targetDomain} domain
// app.use('/assets', createProxyMiddleware({
//     target: `https://${targetDomain}/`,
//     changeOrigin: true,
//     pathRewrite: {
//         '^/assets': '/'
//     },
//     onError: (err, req, res) => {
//         console.error('Proxy error:', err);
//         res.sendStatus(500);
//     }
// }));

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});


I can see pages of "example.com" on localhost:3000. But I have one problem. It is Cors Error. When I am gonna login, I can see cors error like: "Access to XMLHttpRequest at 'https://account.com/api/auto_sign_in' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

As you see at my code, I've already add cors middleware to res and ProxyRes. But I still see the above error. I want to fix cors error with change my code.

0 Answers0