You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

568 lines
19 KiB

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