代码之家  ›  专栏  ›  技术社区  ›  Silent Sea

使用http代理中间件的Node.js代理服务器中的Cors错误

  •  0
  • Silent Sea  · 技术社区  · 2 年前

    这是我的Node.js代理服务器代码。

    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}`);
    });
    
    
    

    我可以在localhost:3000上看到“example.com”的页面。但我有一个问题。这是Cors错误。 当我要登录时,我可以看到如下错误: “在'访问XMLHttpRequesthttps://account.com/api/auto_sign_in'来自原点'http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“access control Allow Origin”标头。“

    正如您在我的代码中看到的,我已经将cors中间件添加到res和ProxyRes中。 但我仍然看到了上述错误。 我想通过更改代码来修复cors错误。

    0 回复  |  直到 2 年前