arnaucube
arnaucube/socketioMEANseedPublic Self-hosted repository
socketioMEANseed/www/node_modules/http-proxy/README.md
www/node_modules/http-proxy/README.mdRaw
  1<p align="center">
  2  <img src="https://raw.github.com/nodejitsu/node-http-proxy/master/doc/logo.png"/>
  3</p>
  4
  5node-http-proxy
  6=======
  7
  8<p align="left">
  9 <a href="https://travis-ci.org/nodejitsu/node-http-proxy" target="_blank">
 10  <img src="https://travis-ci.org/nodejitsu/node-http-proxy.png"/></a>&nbsp;&nbsp;
 11 <a href="https://coveralls.io/r/nodejitsu/node-http-proxy" target="_blank">
 12  <img src="https://coveralls.io/repos/nodejitsu/node-http-proxy/badge.png"/></a>
 13</p>
 14
 15`node-http-proxy` is an HTTP programmable proxying library that supports
 16websockets. It is suitable for implementing components such as reverse
 17proxies and load balancers.
 18
 19### Table of Contents
 20  * [Installation](#installation)
 21  * [Upgrading from 0.8.x ?](#upgrading-from-08x-)
 22  * [Core Concept](#core-concept)
 23  * [Use Cases](#use-cases)
 24    * [Setup a basic stand-alone proxy server](#setup-a-basic-stand-alone-proxy-server)
 25    * [Setup a stand-alone proxy server with custom server logic](#setup-a-stand-alone-proxy-server-with-custom-server-logic)
 26    * [Setup a stand-alone proxy server with proxy request header re-writing](#setup-a-stand-alone-proxy-server-with-proxy-request-header-re-writing)
 27    * [Modify a response from a proxied server](#modify-a-response-from-a-proxied-server)
 28    * [Setup a stand-alone proxy server with latency](#setup-a-stand-alone-proxy-server-with-latency)
 29    * [Using HTTPS](#using-https)
 30    * [Proxying WebSockets](#proxying-websockets)
 31  * [Options](#options)
 32  * [Listening for proxy events](#listening-for-proxy-events)
 33  * [Shutdown](#shutdown)
 34  * [Miscellaneous](#miscellaneous)
 35    * [Test](#test)
 36    * [ProxyTable API](#proxytable-api)
 37    * [Logo](#logo)
 38  * [Contributing and Issues](#contributing-and-issues)
 39  * [License](#license)
 40
 41### Installation
 42
 43`npm install http-proxy --save`
 44
 45**[Back to top](#table-of-contents)**
 46
 47### Upgrading from 0.8.x ?
 48
 49Click [here](UPGRADING.md)
 50
 51**[Back to top](#table-of-contents)**
 52
 53### Core Concept
 54
 55A new proxy is created by calling `createProxyServer` and passing
 56an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L33-L50))
 57
 58```javascript
 59var httpProxy = require('http-proxy');
 60
 61var proxy = httpProxy.createProxyServer(options); // See (†)
 62```
 63†Unless listen(..) is invoked on the object, this does not create a webserver. See below.
 64
 65An object will be returned with four methods:
 66
 67* web `req, res, [options]` (used for proxying regular HTTP(S) requests)
 68* ws `req, socket, head, [options]` (used for proxying WS(S) requests)
 69* listen `port` (a function that wraps the object in a webserver, for your convenience)
 70* close `[callback]` (a function that closes the inner webserver and stops listening on given port)
 71
 72It is then possible to proxy requests by calling these functions
 73
 74```javascript
 75http.createServer(function(req, res) {
 76  proxy.web(req, res, { target: 'http://mytarget.com:8080' });
 77});
 78```
 79
 80Errors can be listened on either using the Event Emitter API
 81
 82```javascript
 83proxy.on('error', function(e) {
 84  ...
 85});
 86```
 87
 88or using the callback API
 89
 90```javascript
 91proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
 92```
 93
 94When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
 95which apply transformations to both the `req` and `res` object.
 96The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
 97The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
 98to the client.
 99
100**[Back to top](#table-of-contents)**
101
102### Use Cases
103
104#### Setup a basic stand-alone proxy server
105
106```js
107var http = require('http'),
108    httpProxy = require('http-proxy');
109//
110// Create your proxy server and set the target in the options.
111//
112httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)
113
114//
115// Create your target server
116//
117http.createServer(function (req, res) {
118  res.writeHead(200, { 'Content-Type': 'text/plain' });
119  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
120  res.end();
121}).listen(9000);
122```
123†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.
124
125**[Back to top](#table-of-contents)**
126
127#### Setup a stand-alone proxy server with custom server logic
128This example show how you can proxy a request using your own HTTP server
129and also you can put your own logic to handle the request.
130
131```js
132var http = require('http'),
133    httpProxy = require('http-proxy');
134
135//
136// Create a proxy server with custom application logic
137//
138var proxy = httpProxy.createProxyServer({});
139
140//
141// Create your custom server and just call `proxy.web()` to proxy
142// a web request to the target passed in the options
143// also you can use `proxy.ws()` to proxy a websockets request
144//
145var server = http.createServer(function(req, res) {
146  // You can define here your custom logic to handle the request
147  // and then proxy the request.
148  proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
149});
150
151console.log("listening on port 5050")
152server.listen(5050);
153```
154
155**[Back to top](#table-of-contents)**
156
157#### Setup a stand-alone proxy server with proxy request header re-writing
158This example shows how you can proxy a request using your own HTTP server that
159modifies the outgoing proxy request by adding a special header.
160
161```js
162var http = require('http'),
163    httpProxy = require('http-proxy');
164
165//
166// Create a proxy server with custom application logic
167//
168var proxy = httpProxy.createProxyServer({});
169
170// To modify the proxy connection before data is sent, you can listen
171// for the 'proxyReq' event. When the event is fired, you will receive
172// the following arguments:
173// (http.ClientRequest proxyReq, http.IncomingMessage req,
174//  http.ServerResponse res, Object options). This mechanism is useful when
175// you need to modify the proxy request before the proxy connection
176// is made to the target.
177//
178proxy.on('proxyReq', function(proxyReq, req, res, options) {
179  proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
180});
181
182var server = http.createServer(function(req, res) {
183  // You can define here your custom logic to handle the request
184  // and then proxy the request.
185  proxy.web(req, res, {
186    target: 'http://127.0.0.1:5060'
187  });
188});
189
190console.log("listening on port 5050")
191server.listen(5050);
192```
193
194**[Back to top](#table-of-contents)**
195
196#### Modify a response from a proxied server
197Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
198
199[Harmon](https://github.com/No9/harmon) allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
200
201**[Back to top](#table-of-contents)**
202
203#### Setup a stand-alone proxy server with latency
204
205```js
206var http = require('http'),
207    httpProxy = require('http-proxy');
208
209//
210// Create a proxy server with latency
211//
212var proxy = httpProxy.createProxyServer();
213
214//
215// Create your server that makes an operation that waits a while
216// and then proxies the request
217//
218http.createServer(function (req, res) {
219  // This simulates an operation that takes 500ms to execute
220  setTimeout(function () {
221    proxy.web(req, res, {
222      target: 'http://localhost:9008'
223    });
224  }, 500);
225}).listen(8008);
226
227//
228// Create your target server
229//
230http.createServer(function (req, res) {
231  res.writeHead(200, { 'Content-Type': 'text/plain' });
232  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
233  res.end();
234}).listen(9008);
235```
236
237**[Back to top](#table-of-contents)**
238
239#### Using HTTPS
240You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.
241
242##### HTTPS -> HTTP
243
244```js
245//
246// Create the HTTPS proxy server in front of a HTTP server
247//
248httpProxy.createServer({
249  target: {
250    host: 'localhost',
251    port: 9009
252  },
253  ssl: {
254    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
255    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
256  }
257}).listen(8009);
258```
259
260##### HTTPS -> HTTPS
261
262```js
263//
264// Create the proxy server listening on port 443
265//
266httpProxy.createServer({
267  ssl: {
268    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
269    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
270  },
271  target: 'https://localhost:9010',
272  secure: true // Depends on your needs, could be false.
273}).listen(443);
274```
275
276**[Back to top](#table-of-contents)**
277
278#### Proxying WebSockets
279You can activate the websocket support for the proxy using `ws:true` in the options.
280
281```js
282//
283// Create a proxy server for websockets
284//
285httpProxy.createServer({
286  target: 'ws://localhost:9014',
287  ws: true
288}).listen(8014);
289```
290
291Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
292
293```js
294//
295// Setup our server to proxy standard HTTP requests
296//
297var proxy = new httpProxy.createProxyServer({
298  target: {
299    host: 'localhost',
300    port: 9015
301  }
302});
303var proxyServer = http.createServer(function (req, res) {
304  proxy.web(req, res);
305});
306
307//
308// Listen to the `upgrade` event and proxy the
309// WebSocket requests as well.
310//
311proxyServer.on('upgrade', function (req, socket, head) {
312  proxy.ws(req, socket, head);
313});
314
315proxyServer.listen(8015);
316```
317
318**[Back to top](#table-of-contents)**
319
320### Options
321
322`httpProxy.createProxyServer` supports the following options:
323
324*  **target**: url string to be parsed with the url module
325*  **forward**: url string to be parsed with the url module
326*  **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)
327*  **ssl**: object to be passed to https.createServer()
328*  **ws**: true/false, if you want to proxy websockets
329*  **xfwd**: true/false, adds x-forward headers
330*  **secure**: true/false, if you want to verify the SSL Certs
331*  **toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
332*  **prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
333*  **ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
334*  **localAddress**: Local interface string to bind for outgoing connections
335*  **changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
336*  **preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
337*  **auth**: Basic authentication i.e. 'user:password' to compute an Authorization header.
338*  **hostRewrite**: rewrites the location hostname on (201/301/302/307/308) redirects.
339*  **autoRewrite**: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
340*  **protocolRewrite**: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
341*  **cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
342   * `false` (default): disable cookie rewriting
343   * String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
344   * Object: mapping of domains to new domains, use `"*"` to match all domains.  
345     For example keep one domain unchanged, rewrite one domain and remove other domains:
346     ```
347     cookieDomainRewrite: {
348       "unchanged.domain": "unchanged.domain",
349       "old.domain": "new.domain",
350       "*": ""
351     }
352     ```
353*  **headers**: object with extra headers to be added to target requests.
354*  **proxyTimeout**: timeout (in millis) when proxy receives no response from target
355
356**NOTE:**
357`options.ws` and `options.ssl` are optional.
358`options.target` and `options.forward` cannot both be missing
359
360If you are using the `proxyServer.listen` method, the following options are also applicable:
361
362 *  **ssl**: object to be passed to https.createServer()
363 *  **ws**: true/false, if you want to proxy websockets
364
365**[Back to top](#table-of-contents)**
366
367### Listening for proxy events
368
369* `error`: The error event is emitted if the request to the target fail. **We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.**
370* `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
371* `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
372* `proxyRes`: This event is emitted if the request to the target got a response.
373* `open`: This event is emitted once the proxy websocket was created and piped into the target websocket.
374* `close`: This event is emitted once the proxy websocket was closed.
375* (DEPRECATED) `proxySocket`: Deprecated in favor of `open`.
376
377```js
378var httpProxy = require('http-proxy');
379// Error example
380//
381// Http Proxy Server with bad target
382//
383var proxy = httpProxy.createServer({
384  target:'http://localhost:9005'
385});
386
387proxy.listen(8005);
388
389//
390// Listen for the `error` event on `proxy`.
391proxy.on('error', function (err, req, res) {
392  res.writeHead(500, {
393    'Content-Type': 'text/plain'
394  });
395
396  res.end('Something went wrong. And we are reporting a custom error message.');
397});
398
399//
400// Listen for the `proxyRes` event on `proxy`.
401//
402proxy.on('proxyRes', function (proxyRes, req, res) {
403  console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
404});
405
406//
407// Listen for the `open` event on `proxy`.
408//
409proxy.on('open', function (proxySocket) {
410  // listen for messages coming FROM the target here
411  proxySocket.on('data', hybiParseAndLogMessage);
412});
413
414//
415// Listen for the `close` event on `proxy`.
416//
417proxy.on('close', function (res, socket, head) {
418  // view disconnected websocket connections
419  console.log('Client disconnected');
420});
421```
422
423**[Back to top](#table-of-contents)**
424
425### Shutdown
426
427* When testing or running server within another program it may be necessary to close the proxy.
428* This will stop the proxy from accepting new connections.
429
430```js
431var proxy = new httpProxy.createProxyServer({
432  target: {
433    host: 'localhost',
434    port: 1337
435  }
436});
437
438proxy.close();
439```
440
441**[Back to top](#table-of-contents)**
442
443### Miscellaneous
444
445#### ProxyTable API
446
447A proxy table API is available through this add-on [module](https://github.com/donasaur/http-proxy-rules), which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
448
449#### Test
450
451```
452$ npm test
453```
454
455#### Logo
456
457Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
458
459**[Back to top](#table-of-contents)**
460
461### Contributing and Issues
462
463* Search on Google/Github
464* If you can't find anything, open an issue
465* If you feel comfortable about fixing the issue, fork the repo
466* Commit to your local branch (which must be different from `master`)
467* Submit your Pull Request (be sure to include tests and update documentation)
468
469**[Back to top](#table-of-contents)**
470
471### License
472
473>The MIT License (MIT)
474>
475>Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
476>
477>Permission is hereby granted, free of charge, to any person obtaining a copy
478>of this software and associated documentation files (the "Software"), to deal
479>in the Software without restriction, including without limitation the rights
480>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
481>copies of the Software, and to permit persons to whom the Software is
482>furnished to do so, subject to the following conditions:
483>
484>The above copyright notice and this permission notice shall be included in
485>all copies or substantial portions of the Software.
486>
487>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
488>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
489>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
490>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
491>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
492>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
493>THE SOFTWARE.