UNPKG

11.8 kBMarkdownView Raw
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`node-http-proxy` is an HTTP programmable proxying library that supports
9websockets. It is suitable for implementing components such as
10proxies and load balancers.
11
12### Build Status
13
14<p align="center">
15 <a href="https://travis-ci.org/nodejitsu/node-http-proxy" target="_blank">
16 <img src="https://travis-ci.org/nodejitsu/node-http-proxy.png"/></a>&nbsp;&nbsp;
17 <a href="https://coveralls.io/r/nodejitsu/node-http-proxy" target="_blank">
18 <img src="https://coveralls.io/repos/nodejitsu/node-http-proxy/badge.png"/></a>
19</p>
20
21### Looking to Upgrade from 0.8.x ? Click [here](UPGRADING.md)
22
23### Core Concept
24
25A new proxy is created by calling `createProxyServer` and passing
26an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L33-L50))
27
28```javascript
29var httpProxy = require('http-proxy');
30
31var proxy = httpProxy.createProxyServer(options);
32```
33
34An object will be returned with four values:
35
36* web `req, res, [options]` (used for proxying regular HTTP(S) requests)
37* ws `req, socket, head, [options]` (used for proxying WS(S) requests)
38* listen `port` (a function that wraps the object in a webserver, for your convenience)
39* close `[callback]` (a function that closes the inner webserver and stops listening on given port)
40
41It is then possible to proxy requests by calling these functions
42
43```javascript
44http.createServer(function(req, res) {
45 proxy.web(req, res, { target: 'http://mytarget.com:8080' });
46});
47```
48
49Errors can be listened on either using the Event Emitter API
50
51```javascript
52proxy.on('error', function(e) {
53 ...
54});
55```
56
57or using the callback API
58
59```javascript
60proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
61```
62
63When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
64which apply transformations to both the `req` and `res` object.
65The first pipeline (ingoing) is responsible for the creation and manipulation of the stream that connects your client to the target.
66The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
67to the client.
68
69
70#### Setup a basic stand-alone proxy server
71
72```js
73var http = require('http'),
74 httpProxy = require('http-proxy');
75//
76// Create your proxy server and set the target in the options.
77//
78httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);
79
80//
81// Create your target server
82//
83http.createServer(function (req, res) {
84 res.writeHead(200, { 'Content-Type': 'text/plain' });
85 res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
86 res.end();
87}).listen(9000);
88```
89
90#### Setup a stand-alone proxy server with custom server logic
91This example show how you can proxy a request using your own HTTP server
92and also you can put your own logic to handle the request.
93
94```js
95var http = require('http'),
96 httpProxy = require('http-proxy');
97
98//
99// Create a proxy server with custom application logic
100//
101var proxy = httpProxy.createProxyServer({});
102
103//
104// Create your custom server and just call `proxy.web()` to proxy
105// a web request to the target passed in the options
106// also you can use `proxy.ws()` to proxy a websockets request
107//
108var server = http.createServer(function(req, res) {
109 // You can define here your custom logic to handle the request
110 // and then proxy the request.
111 proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
112});
113
114console.log("listening on port 5050")
115server.listen(5050);
116```
117#### Modify a response from a proxied server
118Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
119
120[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.
121
122
123#### Setup a stand-alone proxy server with proxy request header re-writing
124This example shows how you can proxy a request using your own HTTP server that
125modifies the outgoing proxy request by adding a special header.
126
127```js
128var http = require('http'),
129 httpProxy = require('http-proxy');
130
131//
132// Create a proxy server with custom application logic
133//
134var proxy = httpProxy.createProxyServer({});
135
136// To modify the proxy connection before data is sent, you can listen
137// for the 'proxyReq' event. When the event is fired, you will receive
138// the following arguments:
139// (http.ClientRequest proxyReq, http.IncomingMessage req,
140// http.ServerResponse res, Object options). This mechanism is useful when
141// you need to modify the proxy request before the proxy connection
142// is made to the target.
143//
144proxy.on('proxyReq', function(proxyReq, req, res, options) {
145 proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
146});
147
148var server = http.createServer(function(req, res) {
149 // You can define here your custom logic to handle the request
150 // and then proxy the request.
151 proxy.web(req, res, {
152 target: 'http://127.0.0.1:5060'
153 });
154});
155
156console.log("listening on port 5050")
157server.listen(5050);
158```
159
160#### Setup a stand-alone proxy server with latency
161
162```js
163var http = require('http'),
164 httpProxy = require('http-proxy');
165
166//
167// Create a proxy server with latency
168//
169var proxy = httpProxy.createProxyServer();
170
171//
172// Create your server that makes an operation that waits a while
173// and then proxies the request
174//
175http.createServer(function (req, res) {
176 // This simulates an operation that takes 500ms to execute
177 setTimeout(function () {
178 proxy.web(req, res, {
179 target: 'http://localhost:9008'
180 });
181 }, 500);
182}).listen(8008);
183
184//
185// Create your target server
186//
187http.createServer(function (req, res) {
188 res.writeHead(200, { 'Content-Type': 'text/plain' });
189 res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
190 res.end();
191}).listen(9008);
192```
193
194#### Listening for proxy events
195
196* `error`: The error event is emitted if the request to the target fail.
197* `proxyRes`: This event is emitted if the request to the target got a response.
198* `open`: This event is emitted once the proxy websocket was created and piped into the target websocket.
199* `close`: This event is emitted once the proxy websocket was closed.
200* (DEPRECATED) `proxySocket`: Deprecated in favor of `open`.
201
202```js
203var httpProxy = require('http-proxy');
204// Error example
205//
206// Http Proxy Server with bad target
207//
208var proxy = httpProxy.createServer({
209 target:'http://localhost:9005'
210});
211
212proxy.listen(8005);
213
214//
215// Listen for the `error` event on `proxy`.
216proxy.on('error', function (err, req, res) {
217 res.writeHead(500, {
218 'Content-Type': 'text/plain'
219 });
220
221 res.end('Something went wrong. And we are reporting a custom error message.');
222});
223
224//
225// Listen for the `proxyRes` event on `proxy`.
226//
227proxy.on('proxyRes', function (proxyRes, req, res) {
228 console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
229});
230
231//
232// Listen for the `open` event on `proxy`.
233//
234proxy.on('open', function (proxySocket) {
235 // listen for messages coming FROM the target here
236 proxySocket.on('data', hybiParseAndLogMessage);
237});
238
239//
240// Listen for the `close` event on `proxy`.
241//
242proxy.on('close', function (req, socket, head) {
243 // view disconnected websocket connections
244 console.log('Client disconnected');
245});
246```
247
248#### Using HTTPS
249You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.
250
251##### HTTPS -> HTTP
252
253```js
254//
255// Create the HTTPS proxy server in front of a HTTP server
256//
257httpProxy.createServer({
258 target: {
259 host: 'localhost',
260 port: 9009
261 },
262 ssl: {
263 key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
264 cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
265 }
266}).listen(8009);
267```
268
269##### HTTPS -> HTTPS
270
271```js
272//
273// Create the proxy server listening on port 443
274//
275httpProxy.createServer({
276 ssl: {
277 key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
278 cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
279 },
280 target: 'https://localhost:9010',
281 secure: true // Depends on your needs, could be false.
282}).listen(443);
283```
284
285#### Proxying WebSockets
286You can activate the websocket support for the proxy using `ws:true` in the options.
287
288```js
289//
290// Create a proxy server for websockets
291//
292httpProxy.createServer({
293 target: 'ws://localhost:9014',
294 ws: true
295}).listen(8014);
296```
297
298Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
299
300```js
301//
302// Setup our server to proxy standard HTTP requests
303//
304var proxy = new httpProxy.createProxyServer({
305 target: {
306 host: 'localhost',
307 port: 9015
308 }
309});
310var proxyServer = http.createServer(function (req, res) {
311 proxy.web(req, res);
312});
313
314//
315// Listen to the `upgrade` event and proxy the
316// WebSocket requests as well.
317//
318proxyServer.on('upgrade', function (req, socket, head) {
319 proxy.ws(req, socket, head);
320});
321
322proxyServer.listen(8015);
323```
324
325### Contributing and Issues
326
327* Search on Google/Github
328* If you can't find anything, open an issue
329* If you feel comfortable about fixing the issue, fork the repo
330* Commit to your local branch (which must be different from `master`)
331* Submit your Pull Request (be sure to include tests and update documentation)
332
333### Options
334
335`httpProxy.createProxyServer` supports the following options:
336
337 * **target**: url string to be parsed with the url module
338 * **forward**: url string to be parsed with the url module
339 * **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)
340 * **secure**: true/false, if you want to verify the SSL Certs
341 * **xfwd**: true/false, adds x-forward headers
342 * **toProxy**: passes the absolute URL as the `path` (useful for proxying to proxies)
343 * **hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects.
344
345If you are using the `proxyServer.listen` method, the following options are also applicable:
346
347 * **ssl**: object to be passed to https.createServer()
348 * **ws**: true/false, if you want to proxy websockets
349
350### Shutdown
351
352* When testing or running server within another program it may be necessary to close the proxy.
353* This will stop the proxy from accepting new connections.
354
355```js
356var proxy = new httpProxy.createProxyServer({
357 target: {
358 host: 'localhost',
359 port: 1337
360 }
361});
362
363proxy.close();
364```
365
366### Test
367
368```
369$ npm test
370```
371
372### Logo
373
374Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
375
376### License
377
378>The MIT License (MIT)
379>
380>Copyright (c) 2010 - 2013 Nodejitsu Inc.
381>
382>Permission is hereby granted, free of charge, to any person obtaining a copy
383>of this software and associated documentation files (the "Software"), to deal
384>in the Software without restriction, including without limitation the rights
385>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
386>copies of the Software, and to permit persons to whom the Software is
387>furnished to do so, subject to the following conditions:
388>
389>The above copyright notice and this permission notice shall be included in
390>all copies or substantial portions of the Software.
391>
392>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
393>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
394>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
395>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
396>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
397>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
398>THE SOFTWARE.
399
400