diff --git a/examples/http/redirect.js b/examples/http/redirect.js new file mode 100644 index 000000000..3e566c659 --- /dev/null +++ b/examples/http/redirect.js @@ -0,0 +1,39 @@ +var util = require('util'), + colors = require('colors'), + http = require('http'), + httpProxy = require('../../lib/http-proxy'); + + +// +// Basic Http Proxy Server +// + +var proxy = httpProxy.createProxyServer(); +http.createServer(function(req, res) { + proxy.web(req, res, { + target: 'http://localhost:9003' + }) +}).listen(8003); +proxy.on('proxyRes', function(proxyRes, req, res, done) { + //check for redirects and follow them + if (proxyRes.statusCode <= 399 && proxyRes.statusCode >= 300 && proxyRes.headers.location) { + proxy.web(req, res, { + target: proxyRes.headers.location + }); + done(); + } +}); +// +// Target Http Server +// +http.createServer(function(req, res) { + res.writeHead(302, { + 'Location': 'http://localhost:9004' + }); + res.end(); +}).listen(9003); + +http.createServer(function(req, res) { + res.write('request successfully redirected to localhost:9004: ' + '\n' + JSON.stringify(req.headers, true, 2)); + res.end(); +}).listen(9004); \ No newline at end of file diff --git a/lib/http-proxy/passes/web-incoming.js b/lib/http-proxy/passes/web-incoming.js index 572c11a8c..c6003ebcc 100644 --- a/lib/http-proxy/passes/web-incoming.js +++ b/lib/http-proxy/passes/web-incoming.js @@ -142,20 +142,28 @@ web_o = Object.keys(web_o).map(function(pass) { (options.buffer || req).pipe(proxyReq); proxyReq.on('response', function(proxyRes) { - if(server) { server.emit('proxyRes', proxyRes, req, res); } - for(var i=0; i < web_o.length; i++) { - if(web_o[i](req, res, proxyRes)) { break; } + var isDone = false + + function done() { + isDone = true; + } + if (server) { + server.emit('proxyRes', proxyRes, req, res, done); } // Allow us to listen when the proxy has completed proxyRes.on('end', function () { server.emit('end', req, res, proxyRes); - }) + }); + if (!isDone) { + for (var i = 0; i < web_o.length; i++) { + if (web_o[i](req, res, proxyRes)) { break; } + } + proxyRes.pipe(res); + } - proxyRes.pipe(res); + //proxyReq.end(); }); - - //proxyReq.end(); } ] // <--