#### Setup a stand-alone proxy server with latency
```js
varhttp=require('http'),
httpProxy=require('http-proxy');
//
// Create a proxy server with latency
//
varproxy=httpProxy.createProxyServer();
//
// Create your server that make an operation that take a while
// and then proxy de request
//
http.createServer(function(req,res){
// This simulate an operation that take 500ms in execute
setTimeout(function(){
proxy.web(req,res,{
target:'http://localhost:9008'
});
},500);
}).listen(8008);
//
// Create your target server
//
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.write('request successfully proxied to: '+req.url+'\n'+JSON.stringify(req.headers,true,2));
res.end();
}).listen(9008);
```
#### Listening for proxy events
*`error`: The error event is emitted if the request to the target fail.
*`proxyRes`: This event is emitted if the request to the target got a response.
```js
varhttpProxy=require('http-proxy');
// Error example
//
// Http Proxy Server with bad target
//
varproxy=httpProxy.createServer({
target:'http://localhost:9005'
});
proxy.listen(8005);
//
// Listen for the `error` event on `proxy`.
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.');
});
//
// Listen for the `proxyRes` event on `proxy`.
//
proxy.on('proxyRes',function(res){
console.log('RAW Response from the target',JSON.stringify(res.headers,true,2));
});
```
#### Using HTTPS
You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.
##### HTTPS -> HTTP
```js
//
// Create the HTTPS proxy server in front of a HTTP server
//
httpProxy.createServer({
target:{
host:'localhost',
port:9009
},
ssl:{
key:fs.readFileSync('valid-ssl-key.pem','utf8'),
cert:fs.readFileSync('valid-ssl-cert.pem','utf8')
}
}).listen(8009);
```
##### HTTPS -> HTTPS
```js
//
// Create the proxy server listening on port 443
//
httpProxy.createServer({
ssl:{
key:fs.readFileSync('valid-ssl-key.pem','utf8'),
cert:fs.readFileSync('valid-ssl-cert.pem','utf8')
},
target:'https://localhost:9010',
secure:true// Depends on your needs, could be false.
}).listen(443);
```
#### Proxying WebSockets
You can activate the websocket support for the proxy using `ws:true` in the options.
```js
//
// Create a proxy server for websockets
//
httpProxy.createServer({
target:'ws://localhost:9014',
ws:true
}).listen(8014);
```
Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
```js
//
// Setup our server to proxy standard HTTP requests
* 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)
### Options
`httpProxy.createProxyServer` supports the following options:
***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
If you are using the `proxyServer.listen` method, the following options are also applicable:
***ssl**: object to be passed to https.createServer()
***ws**: true/false, if you want to proxy websockets
***xfwd**: true/false, adds x-forward headers
### Test
```
$ npm test
```
### Logo
Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
### License
>The MIT License (MIT)
>
>Copyright (c) 2010 - 2013 Nodejitsu Inc.
>
>Permission is hereby granted, free of charge, to any person obtaining a copy
>of this software and associated documentation files (the "Software"), to deal
>in the Software without restriction, including without limitation the rights
Looking to upgrade from `http-proxy@0.x.x` to `http-proxy@1.0`? You've come to the right place!
`http-proxy@1.0` is a from-scratch implementation of `http-proxy` and, as such
brings some breaking changes to APIs.
## Server creation
Available through `.createServer()` or `.createProxyServer()`.
```javascript
httpProxy.createServer({
target:'http://localhost:9003'
}).listen(8003);
```
Check the [README.md](https://github.com/nodejitsu/node-http-proxy/blob/caronte/README.md) for a more detailed explanation of the parameters.
## 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)
```javascript
//
// Create a HTTP Proxy server with a HTTPS target
//
httpProxy.createProxyServer({
target:'https://google.com',
agent:https.globalAgent,
headers:{
host:'google.com'
}
}).listen(8011);
```
Websockets are proxied by the `.ws()` method. The [examples folder](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/websocket) again provides a lot of useful snippets!
It is possible to listen globally on the `error` event on the server. In alternative, a
callback passed to `.web()` or `.ws()` as last parameter is also accepted.
```javascript
varproxy=httpProxy.createServer({
target:'http://localhost:9005'
});
//
// Tell the proxy to listen on port 8000
//
proxy.listen(8005);
//
// Listen for the `error` event on `proxy`.
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.');
});
```
## Dropped
Since the API was rewritten to be extremely flexible we decided to drop some features
which were in the core and delegate them to eventual "userland" modules.
- Middleware API
- ProxyTable API
### Middleware API
The new API makes it really easy to implement code that behaves like the old Middleware API. You can check some examples [here](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/middleware)
The long-term goal of these scripts and documentation is to provide a consistent and well understood benchmarking process for `node-http-proxy` so that performance does not degrade over time. They were initially created to compare the performance of `v0.10.3` and `v1.0.0` (which was a significant rewrite).
## Pre-requisites
All benchmarking shall be done with [wrk](https://github.com/wg/wrk) which _is the same tool used for performance testing by the node.js core team._ **Make sure you have `wrk` installed before continuing**.
```
$ wrk
Usage: wrk <options> <url>
Options:
-c, --connections <n> Connections to keep open
-r, --requests <n> Total requests to make
-t, --threads <n> Number of threads to use
-H, --header <h> Add header to request
-v, --version Print version details
Numeric arguments may include a SI unit (2k, 2M, 2G)
```
## Benchmarks
1.[Simple HTTP benchmark](#simple-http)
### Simple HTTP
_This benchmark requires three terminals running:_
"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.",
"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":{
"test":"NODE_ENV=testing ./node_modules/.bin/mocha $(find test -name '*.test.js')"
"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",
"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> \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",