node-http-proxy icon indicating copy to clipboard operation
node-http-proxy copied to clipboard

[Question] Intercept request and forward it to another proxys

Open wiliame opened this issue 9 years ago • 4 comments

I'm trying to capture a request and decide if I'm going to send it to another PROXY A or to PROXY B or to make a direct connection or return a null response.

There is any example or test or any project that is doing that so I can see a example? Any tip?

I'm going to try this only with HTTP, but the next step will be to make HTTPS work.

For now I have the next code:

const httpProxy = require('http-proxy');

// Instanciate proxy server
var proxy = httpProxy.createProxy({
    secure: false,
    target: {
        https: true,
    }
});

// Add headers
proxy.on('proxyReq', function(proxyReq, req, res, options) {
    proxyReq.setHeader('x-test-header', '123456');
});

// Intercept requests
http.createServer(function (req, res) {
    console.info(req.url);
    let data = url.parse(req.url);

    // return 200 + null response
    if(req.url.match(/retnull/)) {
        return res.end('');
    }

    // forward to proxy A
    if(req.url.match(/proxy-a/)) {
        // TODO
    }

    // forward to proxy B
    if(req.url.match(/proxy-b/)) {
        // TODO
    }

    // direct connection
    proxy.web(req, res, {
        target: {
            host: data.host,
            port: data.port || 80,
        },
    });

}).listen(8000);

wiliame avatar Dec 14 '16 19:12 wiliame

For testing purposes, this is working, there is a better option?

 // forward to proxy A
    if(req.url.match(/proxy-a/)) {
        delete req.headers['host'];
        delete req.headers['connection'];
        delete req.headers['content-length'];

        let bodyData = '';

        req.on('data', (chunk) => {
            bodyData += chunk;
        });

        req.on('end', () => {
            request({
                method: req.method,
                url: req.url,
                proxy: 'http://another-proxy:8080/',
                body: bodyData,
                headers: req.headers,

            }).pipe(res);
        });

        return;
    }

wiliame avatar Dec 14 '16 20:12 wiliame

I provided a fix for the problem.

https://github.com/nodejitsu/node-http-proxy/pull/1128

BernhardRode avatar Jan 03 '17 15:01 BernhardRode

@BernhardRode can you provide an example for my case please?

wiliame avatar Jan 12 '17 23:01 wiliame

What do you mean with example?

Try to checkout/link my #1128 branch... i think it should just work by then.

BernhardRode avatar Jan 13 '17 06:01 BernhardRode