Commit cfe34a20 authored by Leo Iannacone's avatar Leo Iannacone

updated http-proxy - eventemitter3

parent 6a701184
......@@ -5,7 +5,7 @@
node-http-proxy
=======
`node-http-proxy` is an HTTP programmable proxying library that supports
`node-http-proxy` is an HTTP programmable proxying library that supports
websockets. It is suitable for implementing components such as
proxies and load balancers.
......@@ -23,7 +23,7 @@ proxies and load balancers.
### Core Concept
A new proxy is created by calling `createProxyServer` and passing
an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L26-L39))
an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L34-L51))
```javascript
var httpProxy = require('http-proxy');
......@@ -48,7 +48,7 @@ require('http').createServer(function(req, res) {
Errors can be listened on either using the Event Emitter API
```javascript
proxy.on('error', function(e) {
proxy.on('error', function(e) {
...
});
```
......@@ -60,9 +60,9 @@ proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... })
```
When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
which apply transformations to both the `req` and `res` object.
which apply transformations to both the `req` and `res` object.
The first pipeline (ingoing) is responsible for the creation and manipulation of the stream that connects your client to the target.
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
to the client.
......@@ -93,14 +93,14 @@ and also you can put your own logic to handle the request.
```js
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
//
// Create your custom server and just call `proxy.web()` to proxy
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
......@@ -171,7 +171,7 @@ proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
......@@ -251,7 +251,7 @@ var proxyServer = http.createServer(function (req, res) {
});
//
// Listen to the `upgrade` event and proxy the
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
......@@ -263,8 +263,8 @@ proxyServer.listen(8015);
### Contributing and Issues
* Search on Google/Github
* If you can't find anything, open an issue
* Search on Google/Github
* If you can't find anything, open an issue
* If you feel comfortable about fixing the issue, fork the repo
* Commit to your local branch (which must be different from `master`)
* Submit your Pull Request (be sure to include tests and update documentation)
......@@ -273,7 +273,7 @@ proxyServer.listen(8015);
`httpProxy.createProxyServer` supports the following options:
* **target**: url string to be parsed with the url module
* **target**: url string to be parsed with the url module
* **forward**: url string to be parsed with the url module
* **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
* **secure**: true/false, if you want to verify the SSL Certs
......@@ -283,6 +283,7 @@ If you are using the `proxyServer.listen` method, the following options are also
* **ssl**: object to be passed to https.createServer()
* **ws**: true/false, if you want to proxy websockets
* **xfwd**: true/false, adds x-forward headers
* **toProxy**: passes the absolute URL as the `path` (useful for proxying to proxies)
### Test
......
......@@ -16,7 +16,7 @@ Check the [README.md](https://github.com/nodejitsu/node-http-proxy/blob/caronte/
## Proxying
Web proying is done by calling the `.web()` method on a Proxy instance. You can check among some use cases in the [examples folder](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/http)
Web proxying is done by calling the `.web()` method on a Proxy instance. You can check among some use cases in the [examples folder](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/http)
```javascript
//
......
......@@ -8,13 +8,6 @@ var http = require('http'),
*/
module.exports = httpProxy.Server;
module.exports.createProxy = function(options) {
return {
web: httpProxy.createRightProxy('web')(options),
ws: httpProxy.createRightProxy('ws')(options)
};
}
/**
* Creates the proxy server.
*
......@@ -30,7 +23,9 @@ module.exports.createProxy = function(options) {
* @api public
*/
module.exports.createProxyServer = module.exports.createServer = function createProxyServer(options) {
module.exports.createProxyServer =
module.exports.createServer =
module.exports.createProxy = function createProxyServer(options) {
/*
* `options` is needed and it must have the following layout:
*
......@@ -42,6 +37,8 @@ module.exports.createProxyServer = module.exports.createServer = function create
* ws : <true/false, if you want to proxy websockets>
* xfwd : <true/false, adds x-forward headers>
* secure : <true/false, verify SSL certificate>
* toProxy: <true/false, explicitly specify if we are proxying to another proxy>
* localAddress : <Local interface string to bind for outgoing connections>
* }
*
* NOTE: `options.ws` and `options.ssl` are optional.
......
......@@ -44,7 +44,26 @@ common.setupOutgoing = function(outgoing, options, req, forward) {
outgoing.agent = options.agent || false;
outgoing.path = url.parse(req.url).path;
outgoing.localAddress = options.localAddress;
//
// Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
// as node core doesn't handle this COMPLETELY properly yet.
//
if (!outgoing.agent) {
outgoing.headers = outgoing.headers || {};
if (typeof outgoing.headers.connection !== 'string'
|| outgoing.headers.connection.toLowerCase() !== 'upgrade'
) { outgoing.headers.connection = 'close'; }
}
//
// Remark: Can we somehow not use url.parse as a perf optimization?
//
outgoing.path = !options.toProxy
? url.parse(req.url).path
: req.url;
return outgoing;
};
......@@ -75,8 +94,8 @@ common.setupSocket = function(socket) {
};
common.getPort = function(req) {
var res = req.headers.host.match(/:(\d+)/);
return res ?
var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : "";
return res ?
res[1] :
req.connection.pair ? '443' : '80' ;
req.connection.pair ? '443' : '80' ;
}
......@@ -26,15 +26,10 @@ httpProxy.Server = ProxyServer;
*/
function createRightProxy(type) {
var webPasses = Object.keys(web).map(function(pass) {
return web[pass];
});
var wsPasses = Object.keys(ws).map(function(pass) {
return ws[pass];
});
return function(options) {
return function(req, res /*, [head], [opts] */) {
var passes = (type === 'ws') ? (this.wsPasses || wsPasses) : (this.webPasses || webPasses),
var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
args = [].slice.call(arguments),
cntr = args.length - 1,
head, cbl;
......
......@@ -90,6 +90,11 @@ web_o = Object.keys(web_o).map(function(pass) {
*/
function stream(req, res, options, _, server, clb) {
// And we begin!
if (!clb) {
server.emit('start', req, res, options.target)
}
if(options.forward) {
// If forward enable, so just pipe the request
var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
......@@ -104,24 +109,40 @@ web_o = Object.keys(web_o).map(function(pass) {
common.setupOutgoing(options.ssl || {}, options, req)
);
// Ensure we abort proxy if request is aborted
req.on('aborted', function () {
proxyReq.abort();
});
// Handle errors on incoming request as well as it makes sense to
req.on('error', proxyError);
// Error Handler
proxyReq.on('error', function(err){
if(options.buffer) { options.buffer.destroy(); }
proxyReq.on('error', proxyError);
function proxyError (err){
if (clb) {
clb(err, req, res);
} else {
server.emit('error', err, req, res);
}
});
}
(options.buffer || req).pipe(proxyReq);
proxyReq.on('response', function(proxyRes) {
if(server) { server.emit('proxyRes', 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; }
}
// Allow us to listen when the proxy has completed
proxyRes.on('end', function () {
if (!clb) {
server.emit('end', req, res, proxyRes);
}
})
proxyRes.pipe(res);
});
......
......@@ -40,6 +40,8 @@ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
, i;
if (1 === length) {
if (fn.__EE3_once) this.removeListener(event, fn);
switch (len) {
case 1:
fn.call(fn.__EE3_context || this);
......@@ -67,16 +69,14 @@ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
fn.apply(fn.__EE3_context || this, args);
}
if (fn.__EE3_once) this.removeListener(event, fn);
} else {
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
for (i = 0; i < length; fn = listeners[++i]) {
fn.apply(fn.__EE3_context || this, args);
if (fn.__EE3_once) this.removeListener(event, fn);
fn.apply(fn.__EE3_context || this, args);
}
}
......
{
"name": "eventemitter3",
"version": "0.1.1",
"version": "0.1.2",
"description": "EventEmitter3 focuses on performance while maintaining a Node.js AND browser compatible interface. This the source of the same EventEmitter that is used in Primus.",
"main": "index.js",
"scripts": {
......@@ -17,8 +17,12 @@
"Events",
"reactor",
"pub/sub",
"publish",
"subscribe",
"event",
"emitter"
"emitter",
"addListener",
"addEventListener"
],
"author": {
"name": "Arnout Kazemier"
......@@ -28,12 +32,16 @@
"url": "https://github.com/3rd-Eden/EventEmitter3/issues"
},
"devDependencies": {
"mocha": "1.13.x",
"mocha": "1.18.x",
"pre-commit": "0.0.x",
"chai": "1.8.x"
"chai": "1.9.x"
},
"readme": "# EventEmitter3\n\nEventEmitter3 is a faster alternative to EventEmitter2 and the build-in\nEventEmitter that ships within Node.js. It removes some features that you might\nnot need:\n\n- Domain support.\n- Thrown errors when there are no error listeners specified.\n- That a `newListener` event is emitted when an event is emitted.\n- No silly `setMaxListeners`.\n- No silly `listenerCount` function.. Just do `EventEmitter.listeners(event).length`\n\nAnd adds some features you want:\n\n- Emit events with a custom context without binding: `EE.on(event, fn, context)`\n which also works with once `EE.once(event, fn, context)`\n\nIt's a drop in replacement of your existing EventEmitters, but just faster. Free\nperformance, who wouldn't want that.\n\nThe source of the EventEmitter is compatible for browser usage, no fancy pancy\n`Array.isArray` stuff is used, it's just plain ol JavaScript that should even\nwork IE5 if you want to. This module currently serves it's use in\n[Primus](http://github.com/primus/primus)'s client file.\n\n## Installation\n\n```bash\n$ npm install --save eventemitter3\n```\nor as a [component](http://component.io)\n\n```bash\n$ component install eventemitter3\n```\n\nthen\n\n```js\nvar EventEmitter = require('eventemitter3');\n\n// or\n\nvar EventEmitter = require('eventemitter3').EventEmitter;\n```\n\nFor API methods see the official Node.js documentation: \n\nhttp://nodejs.org/api/events.html\n",
"readmeFilename": "README.md",
"_id": "eventemitter3@0.1.1",
"_from": "eventemitter3@*"
"_id": "eventemitter3@0.1.2",
"dist": {
"shasum": "82f49c44c217e6d8cf13be4be6af527f76fecc3b"
},
"_from": "eventemitter3@*",
"_resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-0.1.2.tgz"
}
......@@ -122,6 +122,20 @@ describe('EventEmitter', function tests() {
expect(calls).to.equal(1);
});
it('only emits once if emits are nested inside the listener', function () {
var e = new EventEmitter()
, calls = 0;
e.once('foo', function () {
calls++;
e.emit('foo');
});
e.emit('foo');
expect(e.listeners('foo').length).to.equal(0);
expect(calls).to.equal(1);
});
it('only emits once for multiple events', function () {
var e = new EventEmitter()
, multi = 0
......
{
"name": "http-proxy",
"version": "1.0.2",
"version": "1.1.4",
"repository": {
"type": "git",
"url": "https://github.com/nodejitsu/node-http-proxy.git"
},
"description": "HTTP proxying for the masses",
"author": {
"name": "Nodejitsu Inc.",
......@@ -41,8 +45,15 @@
"node": ">=0.10.0"
},
"license": "MIT",
"readme": "<p align=\"center\">\n <img src=\"https://raw.github.com/nodejitsu/node-http-proxy/master/doc/logo.png\"/>\n</p>\n\nnode-http-proxy\n=======\n\n`node-http-proxy` is an HTTP programmable proxying library that supports \nwebsockets. It is suitable for implementing components such as\nproxies and load balancers.\n\n### Build Status\n\n<p align=\"center\">\n <a href=\"https://travis-ci.org/nodejitsu/node-http-proxy\" target=\"_blank\">\n \t<img src=\"https://travis-ci.org/nodejitsu/node-http-proxy.png\"/></a>&nbsp;&nbsp;\n <a href=\"https://coveralls.io/r/nodejitsu/node-http-proxy\" target=\"_blank\">\n \t<img src=\"https://coveralls.io/repos/nodejitsu/node-http-proxy/badge.png\"/></a>\n</p>\n\n### Looking to Upgrade from 0.8.x ? Click [here](UPGRADING.md)\n\n### Core Concept\n\nA new proxy is created by calling `createProxyServer` and passing\nan `options` object as argument ([valid properties are available here](lib/http-proxy.js#L26-L39)) \n\n```javascript\nvar httpProxy = require('http-proxy');\n\nvar proxy = httpProxy.createProxyServer(options);\n```\n\nAn object will be returned with four values:\n\n* web `req, res, [options]` (used for proxying regular HTTP(S) requests)\n* ws `req, socket, head, [options]` (used for proxying WS(S) requests)\n* listen `port` (a function that wraps the object in a webserver, for your convenience)\n\nIs it then possible to proxy requests by calling these functions\n\n```javascript\nrequire('http').createServer(function(req, res) {\n proxy.web(req, res, { target: 'http://mytarget.com:8080' });\n});\n```\n\nErrors can be listened on either using the Event Emitter API\n\n```javascript\nproxy.on('error', function(e) { \n ...\n});\n```\n\nor using the callback API\n\n```javascript\nproxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });\n```\n\nWhen a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))\nwhich apply transformations to both the `req` and `res` object. \nThe first pipeline (ingoing) is responsible for the creation and manipulation of the stream that connects your client to the target.\nThe second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data \nto the client.\n\n\n#### Setup a basic stand-alone proxy server\n\n```js\nvar http = require('http'),\n httpProxy = require('http-proxy');\n//\n// Create your proxy server and set the target in the options.\n//\nhttpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);\n\n//\n// Create your target server\n//\nhttp.createServer(function (req, res) {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.write('request successfully proxied!' + '\\n' + JSON.stringify(req.headers, true, 2));\n res.end();\n}).listen(9000);\n```\n\n#### Setup a stand-alone proxy server with custom server logic\nThis example show how you can proxy a request using your own HTTP server\nand also you can put your own logic to handle the request.\n\n```js\nvar http = require('http'),\n httpProxy = require('http-proxy');\n \n//\n// Create a proxy server with custom application logic\n//\nvar proxy = httpProxy.createProxyServer({});\n\n//\n// Create your custom server and just call `proxy.web()` to proxy \n// a web request to the target passed in the options\n// also you can use `proxy.ws()` to proxy a websockets request\n//\nvar server = require('http').createServer(function(req, res) {\n // You can define here your custom logic to handle the request\n // and then proxy the request.\n proxy.web(req, res, { target: 'http://127.0.0.1:5060' });\n});\n\nconsole.log(\"listening on port 5050\")\nserver.listen(5050);\n```\n\n#### Setup a stand-alone proxy server with latency\n\n```js\nvar http = require('http'),\n httpProxy = require('http-proxy');\n\n//\n// Create a proxy server with latency\n//\nvar proxy = httpProxy.createProxyServer();\n\n//\n// Create your server that make an operation that take a while\n// and then proxy de request\n//\nhttp.createServer(function (req, res) {\n // This simulate an operation that take 500ms in execute\n setTimeout(function () {\n proxy.web(req, res, {\n target: 'http://localhost:9008'\n });\n }, 500);\n}).listen(8008);\n\n//\n// Create your target server\n//\nhttp.createServer(function (req, res) {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.write('request successfully proxied to: ' + req.url + '\\n' + JSON.stringify(req.headers, true, 2));\n res.end();\n}).listen(9008);\n```\n\n#### Listening for proxy events\n\n* `error`: The error event is emitted if the request to the target fail.\n* `proxyRes`: This event is emitted if the request to the target got a response.\n\n```js\nvar httpProxy = require('http-proxy');\n// Error example\n//\n// Http Proxy Server with bad target\n//\nvar proxy = httpProxy.createServer({\n target:'http://localhost:9005'\n});\n\nproxy.listen(8005);\n\n//\n// Listen for the `error` event on `proxy`.\nproxy.on('error', function (err, req, res) {\n res.writeHead(500, {\n 'Content-Type': 'text/plain'\n });\n \n res.end('Something went wrong. And we are reporting a custom error message.');\n});\n\n//\n// Listen for the `proxyRes` event on `proxy`.\n//\nproxy.on('proxyRes', function (res) {\n console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));\n});\n\n```\n\n#### Using HTTPS\nYou can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.\n\n##### HTTPS -> HTTP\n\n```js\n//\n// Create the HTTPS proxy server in front of a HTTP server\n//\nhttpProxy.createServer({\n target: {\n host: 'localhost',\n port: 9009\n },\n ssl: {\n key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),\n cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')\n }\n}).listen(8009);\n```\n\n##### HTTPS -> HTTPS\n\n```js\n//\n// Create the proxy server listening on port 443\n//\nhttpProxy.createServer({\n ssl: {\n key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),\n cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')\n },\n target: 'https://localhost:9010',\n secure: true // Depends on your needs, could be false.\n}).listen(443);\n```\n\n#### Proxying WebSockets\nYou can activate the websocket support for the proxy using `ws:true` in the options.\n\n```js\n//\n// Create a proxy server for websockets\n//\nhttpProxy.createServer({\n target: 'ws://localhost:9014',\n ws: true\n}).listen(8014);\n```\n\nAlso you can proxy the websocket requests just calling the `ws(req, socket, head)` method.\n\n```js\n//\n// Setup our server to proxy standard HTTP requests\n//\nvar proxy = new httpProxy.createProxyServer({\n target: {\n host: 'localhost',\n port: 9015\n }\n});\nvar proxyServer = http.createServer(function (req, res) {\n proxy.web(req, res);\n});\n\n//\n// Listen to the `upgrade` event and proxy the \n// WebSocket requests as well.\n//\nproxyServer.on('upgrade', function (req, socket, head) {\n proxy.ws(req, socket, head);\n});\n\nproxyServer.listen(8015);\n```\n\n### Contributing and Issues\n\n* Search on Google/Github \n* If you can't find anything, open an issue \n* If you feel comfortable about fixing the issue, fork the repo\n* Commit to your local branch (which must be different from `master`)\n* Submit your Pull Request (be sure to include tests and update documentation)\n\n### Options\n\n`httpProxy.createProxyServer` supports the following options:\n\n * **target**: url string to be parsed with the url module \n * **forward**: url string to be parsed with the url module\n * **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)\n * **secure**: true/false, if you want to verify the SSL Certs\n\nIf you are using the `proxyServer.listen` method, the following options are also applicable:\n\n * **ssl**: object to be passed to https.createServer()\n * **ws**: true/false, if you want to proxy websockets\n * **xfwd**: true/false, adds x-forward headers\n\n\n### Test\n\n```\n$ npm test\n```\n\n### Logo\n\nLogo created by [Diego Pasquali](http://dribbble.com/diegopq)\n\n### License\n\n>The MIT License (MIT)\n>\n>Copyright (c) 2010 - 2013 Nodejitsu Inc.\n>\n>Permission is hereby granted, free of charge, to any person obtaining a copy\n>of this software and associated documentation files (the \"Software\"), to deal\n>in the Software without restriction, including without limitation the rights\n>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n>copies of the Software, and to permit persons to whom the Software is\n>furnished to do so, subject to the following conditions:\n>\n>The above copyright notice and this permission notice shall be included in\n>all copies or substantial portions of the Software.\n>\n>THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n>THE SOFTWARE.\n\n\n",
"readme": "<p align=\"center\">\n <img src=\"https://raw.github.com/nodejitsu/node-http-proxy/master/doc/logo.png\"/>\n</p>\n\nnode-http-proxy\n=======\n\n`node-http-proxy` is an HTTP programmable proxying library that supports\nwebsockets. It is suitable for implementing components such as\nproxies and load balancers.\n\n### Build Status\n\n<p align=\"center\">\n <a href=\"https://travis-ci.org/nodejitsu/node-http-proxy\" target=\"_blank\">\n \t<img src=\"https://travis-ci.org/nodejitsu/node-http-proxy.png\"/></a>&nbsp;&nbsp;\n <a href=\"https://coveralls.io/r/nodejitsu/node-http-proxy\" target=\"_blank\">\n \t<img src=\"https://coveralls.io/repos/nodejitsu/node-http-proxy/badge.png\"/></a>\n</p>\n\n### Looking to Upgrade from 0.8.x ? Click [here](UPGRADING.md)\n\n### Core Concept\n\nA new proxy is created by calling `createProxyServer` and passing\nan `options` object as argument ([valid properties are available here](lib/http-proxy.js#L34-L51))\n\n```javascript\nvar httpProxy = require('http-proxy');\n\nvar proxy = httpProxy.createProxyServer(options);\n```\n\nAn object will be returned with four values:\n\n* web `req, res, [options]` (used for proxying regular HTTP(S) requests)\n* ws `req, socket, head, [options]` (used for proxying WS(S) requests)\n* listen `port` (a function that wraps the object in a webserver, for your convenience)\n\nIs it then possible to proxy requests by calling these functions\n\n```javascript\nrequire('http').createServer(function(req, res) {\n proxy.web(req, res, { target: 'http://mytarget.com:8080' });\n});\n```\n\nErrors can be listened on either using the Event Emitter API\n\n```javascript\nproxy.on('error', function(e) {\n ...\n});\n```\n\nor using the callback API\n\n```javascript\nproxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });\n```\n\nWhen a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))\nwhich apply transformations to both the `req` and `res` object.\nThe first pipeline (ingoing) is responsible for the creation and manipulation of the stream that connects your client to the target.\nThe second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data\nto the client.\n\n\n#### Setup a basic stand-alone proxy server\n\n```js\nvar http = require('http'),\n httpProxy = require('http-proxy');\n//\n// Create your proxy server and set the target in the options.\n//\nhttpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);\n\n//\n// Create your target server\n//\nhttp.createServer(function (req, res) {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.write('request successfully proxied!' + '\\n' + JSON.stringify(req.headers, true, 2));\n res.end();\n}).listen(9000);\n```\n\n#### Setup a stand-alone proxy server with custom server logic\nThis example show how you can proxy a request using your own HTTP server\nand also you can put your own logic to handle the request.\n\n```js\nvar http = require('http'),\n httpProxy = require('http-proxy');\n\n//\n// Create a proxy server with custom application logic\n//\nvar proxy = httpProxy.createProxyServer({});\n\n//\n// Create your custom server and just call `proxy.web()` to proxy\n// a web request to the target passed in the options\n// also you can use `proxy.ws()` to proxy a websockets request\n//\nvar server = require('http').createServer(function(req, res) {\n // You can define here your custom logic to handle the request\n // and then proxy the request.\n proxy.web(req, res, { target: 'http://127.0.0.1:5060' });\n});\n\nconsole.log(\"listening on port 5050\")\nserver.listen(5050);\n```\n\n#### Setup a stand-alone proxy server with latency\n\n```js\nvar http = require('http'),\n httpProxy = require('http-proxy');\n\n//\n// Create a proxy server with latency\n//\nvar proxy = httpProxy.createProxyServer();\n\n//\n// Create your server that make an operation that take a while\n// and then proxy de request\n//\nhttp.createServer(function (req, res) {\n // This simulate an operation that take 500ms in execute\n setTimeout(function () {\n proxy.web(req, res, {\n target: 'http://localhost:9008'\n });\n }, 500);\n}).listen(8008);\n\n//\n// Create your target server\n//\nhttp.createServer(function (req, res) {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.write('request successfully proxied to: ' + req.url + '\\n' + JSON.stringify(req.headers, true, 2));\n res.end();\n}).listen(9008);\n```\n\n#### Listening for proxy events\n\n* `error`: The error event is emitted if the request to the target fail.\n* `proxyRes`: This event is emitted if the request to the target got a response.\n\n```js\nvar httpProxy = require('http-proxy');\n// Error example\n//\n// Http Proxy Server with bad target\n//\nvar proxy = httpProxy.createServer({\n target:'http://localhost:9005'\n});\n\nproxy.listen(8005);\n\n//\n// Listen for the `error` event on `proxy`.\nproxy.on('error', function (err, req, res) {\n res.writeHead(500, {\n 'Content-Type': 'text/plain'\n });\n\n res.end('Something went wrong. And we are reporting a custom error message.');\n});\n\n//\n// Listen for the `proxyRes` event on `proxy`.\n//\nproxy.on('proxyRes', function (res) {\n console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));\n});\n\n```\n\n#### Using HTTPS\nYou can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.\n\n##### HTTPS -> HTTP\n\n```js\n//\n// Create the HTTPS proxy server in front of a HTTP server\n//\nhttpProxy.createServer({\n target: {\n host: 'localhost',\n port: 9009\n },\n ssl: {\n key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),\n cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')\n }\n}).listen(8009);\n```\n\n##### HTTPS -> HTTPS\n\n```js\n//\n// Create the proxy server listening on port 443\n//\nhttpProxy.createServer({\n ssl: {\n key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),\n cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')\n },\n target: 'https://localhost:9010',\n secure: true // Depends on your needs, could be false.\n}).listen(443);\n```\n\n#### Proxying WebSockets\nYou can activate the websocket support for the proxy using `ws:true` in the options.\n\n```js\n//\n// Create a proxy server for websockets\n//\nhttpProxy.createServer({\n target: 'ws://localhost:9014',\n ws: true\n}).listen(8014);\n```\n\nAlso you can proxy the websocket requests just calling the `ws(req, socket, head)` method.\n\n```js\n//\n// Setup our server to proxy standard HTTP requests\n//\nvar proxy = new httpProxy.createProxyServer({\n target: {\n host: 'localhost',\n port: 9015\n }\n});\nvar proxyServer = http.createServer(function (req, res) {\n proxy.web(req, res);\n});\n\n//\n// Listen to the `upgrade` event and proxy the\n// WebSocket requests as well.\n//\nproxyServer.on('upgrade', function (req, socket, head) {\n proxy.ws(req, socket, head);\n});\n\nproxyServer.listen(8015);\n```\n\n### Contributing and Issues\n\n* Search on Google/Github\n* If you can't find anything, open an issue\n* If you feel comfortable about fixing the issue, fork the repo\n* Commit to your local branch (which must be different from `master`)\n* Submit your Pull Request (be sure to include tests and update documentation)\n\n### Options\n\n`httpProxy.createProxyServer` supports the following options:\n\n * **target**: url string to be parsed with the url module\n * **forward**: url string to be parsed with the url module\n * **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)\n * **secure**: true/false, if you want to verify the SSL Certs\n\nIf you are using the `proxyServer.listen` method, the following options are also applicable:\n\n * **ssl**: object to be passed to https.createServer()\n * **ws**: true/false, if you want to proxy websockets\n * **xfwd**: true/false, adds x-forward headers\n * **toProxy**: passes the absolute URL as the `path` (useful for proxying to proxies)\n\n\n### Test\n\n```\n$ npm test\n```\n\n### Logo\n\nLogo created by [Diego Pasquali](http://dribbble.com/diegopq)\n\n### License\n\n>The MIT License (MIT)\n>\n>Copyright (c) 2010 - 2013 Nodejitsu Inc.\n>\n>Permission is hereby granted, free of charge, to any person obtaining a copy\n>of this software and associated documentation files (the \"Software\"), to deal\n>in the Software without restriction, including without limitation the rights\n>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n>copies of the Software, and to permit persons to whom the Software is\n>furnished to do so, subject to the following conditions:\n>\n>The above copyright notice and this permission notice shall be included in\n>all copies or substantial portions of the Software.\n>\n>THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n>THE SOFTWARE.\n\n\n",
"readmeFilename": "README.md",
"_id": "http-proxy@1.0.2",
"_from": "http-proxy@*"
"bugs": {
"url": "https://github.com/nodejitsu/node-http-proxy/issues"
},
"_id": "http-proxy@1.1.4",
"dist": {
"shasum": "eeee438c39b9ddeac5b475f5e886c5377cb4a8d0"
},
"_from": "http-proxy@1.1.4",
"_resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.1.4.tgz"
}
......@@ -15,6 +15,7 @@ describe('lib/http-proxy/common.js', function () {
port : 'you',
},
headers: {'fizz': 'bang', 'overwritten':true},
localAddress: 'local.address',
},
{
method : 'i',
......@@ -34,6 +35,49 @@ describe('lib/http-proxy/common.js', function () {
expect(outgoing.headers.pro).to.eql('xy');
expect(outgoing.headers.fizz).to.eql('bang');
expect(outgoing.headers.overwritten).to.eql(true);
expect(outgoing.localAddress).to.eql('local.address');
});
it('should not override agentless upgrade header', function () {
var outgoing = {};
common.setupOutgoing(outgoing,
{
agent: undefined,
target: {
host : 'hey',
hostname : 'how',
socketPath: 'are',
port : 'you',
},
headers: {'connection': 'upgrade'},
},
{
method : 'i',
url : 'am',
headers : {'pro':'xy','overwritten':false}
});
expect(outgoing.headers.connection).to.eql('upgrade');
});
it('should override agentless non-upgrade header to close', function () {
var outgoing = {};
common.setupOutgoing(outgoing,
{
agent: undefined,
target: {
host : 'hey',
hostname : 'how',
socketPath: 'are',
port : 'you',
},
headers: {'connection': 'xyz'},
},
{
method : 'i',
url : 'am',
headers : {'pro':'xy','overwritten':false}
});
expect(outgoing.headers.connection).to.eql('close');
});
it('should set the agent to false if none is given', function () {
......
......@@ -127,4 +127,32 @@ describe('#createProxyServer.web() using own http server', function () {
method: 'GET',
}, function() {}).end();
});
it('should proxy the request and provide a proxyRes event with the request and response parameters', function(done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080'
});
function requestHandler(req, res) {
proxy.once('proxyRes', function (proxyRes, pReq, pRes) {
source.close();
proxyServer.close();
expect(pReq).to.be.equal(req);
expect(pRes).to.be.equal(res);
done();
});
proxy.web(req, res);
}
var proxyServer = http.createServer(requestHandler);
var source = http.createServer(function(req, res) {
res.end('Response');
});
proxyServer.listen('8084');
source.listen('8080');
http.request('http://127.0.0.1:8084', function() {}).end();
});
});
\ No newline at end of file
......@@ -78,14 +78,14 @@ describe('lib/http-proxy.js', function() {
});
source.listen(ports.source);
http.request({
hostname: '127.0.0.1',
port: ports.proxy,
method: 'POST',
headers: {
'x-forwarded-for': '127.0.0.1'
}
}
}, function() {}).end();
});
});
......@@ -105,7 +105,7 @@ describe('lib/http-proxy.js', function() {
});
source.listen(ports.source);
http.request({
hostname: '127.0.0.1',
port: ports.proxy,
......@@ -117,7 +117,7 @@ describe('lib/http-proxy.js', function() {
expect(data.toString()).to.eql('Hello from ' + ports.source);
});
res.on('end', function () {
res.on('end', function () {
source.close();
proxy._server.close();
done();
......@@ -141,7 +141,7 @@ describe('lib/http-proxy.js', function() {
})
proxy.listen(ports.proxy);
http.request({
hostname: '127.0.0.1',
port: ports.proxy,
......@@ -159,6 +159,11 @@ describe('lib/http-proxy.js', function() {
timeout: 3
}).listen(ports.proxy);
proxy.on('error', function (e) {
expect(e).to.be.an(Error);
expect(e.code).to.be.eql('ECONNRESET');
});
var source = http.createServer(function(req, res) {
setTimeout(function () {
res.end('At this point the socket should be closed');
......@@ -207,7 +212,7 @@ describe('lib/http-proxy.js', function() {
// proxy.ee.on('http-proxy:**', function (uno, dos, tres) {
// events.push(this.event);
// })
// http.request({
// hostname: '127.0.0.1',
// port: '8081',
......@@ -314,4 +319,4 @@ describe('lib/http-proxy.js', function() {
})
});
})
});
\ No newline at end of file
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment