Merge pull request #897 from lbrucher/issue-896

Issue #896: provide a "proxyReq" event also for websocket connections.
This commit is contained in:
Jarrett Cruger 2015-10-22 19:26:02 -04:00
commit 0bc4c783ca
3 changed files with 49 additions and 0 deletions

View File

@ -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.

View File

@ -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) {

View File

@ -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, socket, options, head) {
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');
});
});
});
})
});