diff --git a/README.md b/README.md index 162bde9b7..0bc800fc8 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,8 @@ http.createServer(function (req, res) { #### Listening for proxy events * `error`: The error event is emitted if the request to the target fail. +* `proxyReq`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connections +* `proxyReqWs`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connections * `proxyRes`: This event is emitted if the request to the target got a response. * `open`: This event is emitted once the proxy websocket was created and piped into the target websocket. * `close`: This event is emitted once the proxy websocket was closed. diff --git a/lib/http-proxy/passes/ws-incoming.js b/lib/http-proxy/passes/ws-incoming.js index f51785749..87f5fe1a0 100644 --- a/lib/http-proxy/passes/ws-incoming.js +++ b/lib/http-proxy/passes/ws-incoming.js @@ -87,6 +87,10 @@ var passes = exports; var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request( common.setupOutgoing(options.ssl || {}, options, req) ); + + // Enable developers to modify the proxyReq before headers are sent + if(server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); } + // Error Handler proxyReq.on('error', onOutgoingError); proxyReq.on('response', function (res) { diff --git a/test/lib-http-proxy-test.js b/test/lib-http-proxy-test.js index d9eea5150..08403828b 100644 --- a/test/lib-http-proxy-test.js +++ b/test/lib-http-proxy-test.js @@ -444,6 +444,49 @@ describe('lib/http-proxy.js', function() { headers.push('Set-Cookie: test2=test2'); }); }); + + it('should detect a proxyReq event and modify headers', function (done) { + var ports = { source: gen.port, proxy: gen.port }, + proxy, + proxyServer, + destiny; + + proxy = httpProxy.createProxyServer({ + target: 'ws://127.0.0.1:' + ports.source, + ws: true + }); + + proxy.on('proxyReqWs', function(proxyReq, req, res, options) { + proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); + }); + + proxyServer = proxy.listen(ports.proxy); + + destiny = new ws.Server({ port: ports.source }, function () { + var client = new ws('ws://127.0.0.1:' + ports.proxy); + + client.on('open', function () { + client.send('hello there'); + }); + + client.on('message', function (msg) { + expect(msg).to.be('Hello over websockets'); + client.close(); + proxyServer.close(); + destiny.close(); + done(); + }); + }); + + destiny.on('connection', function (socket) { + expect(socket.upgradeReq.headers['x-special-proxy-header']).to.eql('foobar'); + + socket.on('message', function (msg) { + expect(msg).to.be('hello there'); + socket.send('Hello over websockets'); + }); + }); + }); }) });