Skip to content

Commit

Permalink
Merge pull request #32 from trbngr/master
Browse files Browse the repository at this point in the history
Enable subscription to the http-proxy on onProxyReq event.
  • Loading branch information
chimurai committed Sep 28, 2015
2 parents 490097b + ec6f428 commit 742c0ae
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Expand Up @@ -208,6 +208,14 @@ var server = app.listen(3000);
}
```

* **option.onProxyReq**: function, subscribe to http-proxy's proxyReq event.
```javascript
function onProxyReq(proxyReq, req, res) {
// add custom header to request
proxyReq.setHeader('x-added', 'foobar');
// or log the req
}

* (DEPRECATED) **option.proxyHost**: Use `option.changeOrigin = true` instead.

The following options are provided by the underlying [http-proxy](https://www.npmjs.com/package/http-proxy).
Expand Down
5 changes: 5 additions & 0 deletions index.js
Expand Up @@ -23,6 +23,11 @@ var httpProxyMiddleware = function (context, opts) {
proxy.on('proxyRes', proxyOptions.onProxyRes);
}

// Custom listener for the `proxyReq` event on `proxy`.
if (_.isFunction(proxyOptions.onProxyReq)) {
proxy.on('proxyReq', proxyOptions.onProxyReq);
}

// Custom listener for the `error` event on `proxy`.
var onProxyError = getProxyErrorHandler();
// handle error and close connection properly
Expand Down
38 changes: 38 additions & 0 deletions test/http-proxy-middleware.spec.js
Expand Up @@ -424,6 +424,44 @@ describe('http-proxy-middleware in actual server', function () {
});
});

describe('option.onProxyReq', function () {
var proxyServer, targetServer;
var receivedRequest;

beforeEach(function (done) {
var fnOnProxyReq = function (proxyReq, req, res) {
proxyReq.setHeader('x-added', 'foobar'); // add custom header to request
};

var mw_proxy = proxyMiddleware('/api', {
target: 'http://localhost:8000',
onProxyReq: fnOnProxyReq
});

var mw_target = function (req, res, next) {
receivedRequest = req;
res.write(req.url); // respond with req.url
res.end();
};

proxyServer = createServer(3000, mw_proxy);
targetServer = createServer(8000, mw_target);

http.get('http://localhost:3000/api/foo/bar', function () {
done();
});
});

afterEach(function () {
proxyServer.close();
targetServer.close();
});

it('should add `x-added` as custom header to request"', function () {
expect(receivedRequest.headers['x-added']).to.equal('foobar');
});
});

describe('option.pathRewrite', function () {
var proxyServer, targetServer;
var responseBody;
Expand Down

0 comments on commit 742c0ae

Please sign in to comment.