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.

491 lines
18 KiB

4 years ago
  1. # http-proxy-middleware
  2. [![Build Status](https://img.shields.io/travis/chimurai/http-proxy-middleware/master.svg?style=flat-square)](https://travis-ci.org/chimurai/http-proxy-middleware)
  3. [![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square)](https://coveralls.io/r/chimurai/http-proxy-middleware)
  4. [![dependency Status](https://img.shields.io/david/chimurai/http-proxy-middleware.svg?style=flat-square)](https://david-dm.org/chimurai/http-proxy-middleware#info=dependencies)
  5. [![dependency Status](https://snyk.io/test/npm/http-proxy-middleware/badge.svg)](https://snyk.io/test/npm/http-proxy-middleware)
  6. [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
  7. Node.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/strongloop/express), [browser-sync](https://github.com/BrowserSync/browser-sync) and [many more](#compatible-servers).
  8. Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/nodejitsu/node-http-proxy.svg?style=social&label=Star)](https://github.com/nodejitsu/node-http-proxy)
  9. ## TL;DR
  10. Proxy `/api` requests to `http://www.example.org`
  11. ```javascript
  12. var express = require('express')
  13. var proxy = require('http-proxy-middleware')
  14. var app = express()
  15. app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
  16. app.listen(3000)
  17. // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
  18. ```
  19. _All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options).
  20. :bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based).
  21. ## Table of Contents
  22. <!-- MarkdownTOC autolink=true bracket=round depth=2 -->
  23. - [Install](#install)
  24. - [Core concept](#core-concept)
  25. - [Example](#example)
  26. - [Context matching](#context-matching)
  27. - [Options](#options)
  28. - [http-proxy-middleware options](#http-proxy-middleware-options)
  29. - [http-proxy events](#http-proxy-events)
  30. - [http-proxy options](#http-proxy-options)
  31. - [Shorthand](#shorthand)
  32. - [app.use\(path, proxy\)](#appusepath-proxy)
  33. - [WebSocket](#websocket)
  34. - [External WebSocket upgrade](#external-websocket-upgrade)
  35. - [Working examples](#working-examples)
  36. - [Recipes](#recipes)
  37. - [Compatible servers](#compatible-servers)
  38. - [Tests](#tests)
  39. - [Changelog](#changelog)
  40. - [License](#license)
  41. <!-- /MarkdownTOC -->
  42. ## Install
  43. ```javascript
  44. $ npm install --save-dev http-proxy-middleware
  45. ```
  46. ## Core concept
  47. Proxy middleware configuration.
  48. #### proxy([context,] config)
  49. ```javascript
  50. var proxy = require('http-proxy-middleware')
  51. var apiProxy = proxy('/api', { target: 'http://www.example.org' })
  52. // \____/ \_____________________________/
  53. // | |
  54. // context options
  55. // 'apiProxy' is now ready to be used as middleware in a server.
  56. ```
  57. - **context**: Determine which requests should be proxied to the target host.
  58. (more on [context matching](#context-matching))
  59. - **options.target**: target host to proxy to. _(protocol + host)_
  60. (full list of [`http-proxy-middleware` configuration options](#options))
  61. #### proxy(uri [, config])
  62. ```javascript
  63. // shorthand syntax for the example above:
  64. var apiProxy = proxy('http://www.example.org/api')
  65. ```
  66. More about the [shorthand configuration](#shorthand).
  67. ## Example
  68. An example with `express` server.
  69. ```javascript
  70. // include dependencies
  71. var express = require('express')
  72. var proxy = require('http-proxy-middleware')
  73. // proxy middleware options
  74. var options = {
  75. target: 'http://www.example.org', // target host
  76. changeOrigin: true, // needed for virtual hosted sites
  77. ws: true, // proxy websockets
  78. pathRewrite: {
  79. '^/api/old-path': '/api/new-path', // rewrite path
  80. '^/api/remove/path': '/path' // remove base path
  81. },
  82. router: {
  83. // when request.headers.host == 'dev.localhost:3000',
  84. // override target 'http://www.example.org' to 'http://localhost:8000'
  85. 'dev.localhost:3000': 'http://localhost:8000'
  86. }
  87. }
  88. // create the proxy (without context)
  89. var exampleProxy = proxy(options)
  90. // mount `exampleProxy` in web server
  91. var app = express()
  92. app.use('/api', exampleProxy)
  93. app.listen(3000)
  94. ```
  95. ## Context matching
  96. Providing an alternative way to decide which requests should be proxied; In case you are not able to use the server's [`path` parameter](http://expressjs.com/en/4x/api.html#app.use) to mount the proxy or when you need more flexibility.
  97. [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching.
  98. ```
  99. foo://example.com:8042/over/there?name=ferret#nose
  100. \_/ \______________/\_________/ \_________/ \__/
  101. | | | | |
  102. scheme authority path query fragment
  103. ```
  104. - **path matching**
  105. - `proxy({...})` - matches any path, all requests will be proxied.
  106. - `proxy('/', {...})` - matches any path, all requests will be proxied.
  107. - `proxy('/api', {...})` - matches paths starting with `/api`
  108. - **multiple path matching**
  109. - `proxy(['/api', '/ajax', '/someotherpath'], {...})`
  110. - **wildcard path matching**
  111. For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples.
  112. - `proxy('**', {...})` matches any path, all requests will be proxied.
  113. - `proxy('**/*.html', {...})` matches any path which ends with `.html`
  114. - `proxy('/*.html', {...})` matches paths directly under path-absolute
  115. - `proxy('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api`
  116. - `proxy(['/api/**', '/ajax/**'], {...})` combine multiple patterns
  117. - `proxy(['/api/**', '!**/bad.json'], {...})` exclusion
  118. **Note**: In multiple path matching, you cannot use string paths and wildcard paths together.
  119. - **custom matching**
  120. For full control you can provide a custom function to determine which requests should be proxied or not.
  121. ```javascript
  122. /**
  123. * @return {Boolean}
  124. */
  125. var filter = function(pathname, req) {
  126. return pathname.match('^/api') && req.method === 'GET'
  127. }
  128. var apiProxy = proxy(filter, { target: 'http://www.example.org' })
  129. ```
  130. ## Options
  131. ### http-proxy-middleware options
  132. - **option.pathRewrite**: object/function, rewrite target's url path. Object-keys will be used as _RegExp_ to match paths.
  133. ```javascript
  134. // rewrite path
  135. pathRewrite: {'^/old/api' : '/new/api'}
  136. // remove path
  137. pathRewrite: {'^/remove/api' : ''}
  138. // add base path
  139. pathRewrite: {'^/' : '/basepath/'}
  140. // custom rewriting
  141. pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
  142. ```
  143. - **option.router**: object/function, re-target `option.target` for specific requests.
  144. ```javascript
  145. // Use `host` and/or `path` to match requests. First match will be used.
  146. // The order of the configuration matters.
  147. router: {
  148. 'integration.localhost:3000' : 'http://localhost:8001', // host only
  149. 'staging.localhost:3000' : 'http://localhost:8002', // host only
  150. 'localhost:3000/api' : 'http://localhost:8003', // host + path
  151. '/rest' : 'http://localhost:8004' // path only
  152. }
  153. // Custom router function
  154. router: function(req) {
  155. return 'http://localhost:8004';
  156. }
  157. ```
  158. - **option.logLevel**: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: `'info'`
  159. - **option.logProvider**: function, modify or replace log provider. Default: `console`.
  160. ```javascript
  161. // simple replace
  162. function logProvider(provider) {
  163. // replace the default console log provider.
  164. return require('winston')
  165. }
  166. ```
  167. ```javascript
  168. // verbose replacement
  169. function logProvider(provider) {
  170. var logger = new (require('winston')).Logger()
  171. var myCustomProvider = {
  172. log: logger.log,
  173. debug: logger.debug,
  174. info: logger.info,
  175. warn: logger.warn,
  176. error: logger.error
  177. }
  178. return myCustomProvider
  179. }
  180. ```
  181. - (DEPRECATED) **option.proxyHost**: Use `option.changeOrigin = true` instead.
  182. - (DEPRECATED) **option.proxyTable**: Use `option.router` instead.
  183. ### http-proxy events
  184. Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events):
  185. - **option.onError**: function, subscribe to http-proxy's `error` event for custom error handling.
  186. ```javascript
  187. function onError(err, req, res) {
  188. res.writeHead(500, {
  189. 'Content-Type': 'text/plain'
  190. })
  191. res.end(
  192. 'Something went wrong. And we are reporting a custom error message.'
  193. )
  194. }
  195. ```
  196. - **option.onProxyRes**: function, subscribe to http-proxy's `proxyRes` event.
  197. ```javascript
  198. function onProxyRes(proxyRes, req, res) {
  199. proxyRes.headers['x-added'] = 'foobar' // add new header to response
  200. delete proxyRes.headers['x-removed'] // remove header from response
  201. }
  202. ```
  203. - **option.onProxyReq**: function, subscribe to http-proxy's `proxyReq` event.
  204. ```javascript
  205. function onProxyReq(proxyReq, req, res) {
  206. // add custom header to request
  207. proxyReq.setHeader('x-added', 'foobar')
  208. // or log the req
  209. }
  210. ```
  211. - **option.onProxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event.
  212. ```javascript
  213. function onProxyReqWs(proxyReq, req, socket, options, head) {
  214. // add custom header
  215. proxyReq.setHeader('X-Special-Proxy-Header', 'foobar')
  216. }
  217. ```
  218. - **option.onOpen**: function, subscribe to http-proxy's `open` event.
  219. ```javascript
  220. function onOpen(proxySocket) {
  221. // listen for messages coming FROM the target here
  222. proxySocket.on('data', hybiParseAndLogMessage)
  223. }
  224. ```
  225. - **option.onClose**: function, subscribe to http-proxy's `close` event.
  226. ```javascript
  227. function onClose(res, socket, head) {
  228. // view disconnected websocket connections
  229. console.log('Client disconnected')
  230. }
  231. ```
  232. ### http-proxy options
  233. The following options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy#options) library.
  234. - **option.target**: url string to be parsed with the url module
  235. - **option.forward**: url string to be parsed with the url module
  236. - **option.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)
  237. - **option.ssl**: object to be passed to https.createServer()
  238. - **option.ws**: true/false: if you want to proxy websockets
  239. - **option.xfwd**: true/false, adds x-forward headers
  240. - **option.secure**: true/false, if you want to verify the SSL Certs
  241. - **option.toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies)
  242. - **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
  243. - **option.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).
  244. - **option.localAddress** : Local interface string to bind for outgoing connections
  245. - **option.changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL
  246. - **option.preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key
  247. - **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header.
  248. - **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects.
  249. - **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
  250. - **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null.
  251. - **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:
  252. - `false` (default): disable cookie rewriting
  253. - String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`.
  254. - Object: mapping of domains to new domains, use `"*"` to match all domains.
  255. For example keep one domain unchanged, rewrite one domain and remove other domains:
  256. ```
  257. cookieDomainRewrite: {
  258. "unchanged.domain": "unchanged.domain",
  259. "old.domain": "new.domain",
  260. "*": ""
  261. }
  262. ```
  263. - **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:
  264. - `false` (default): disable cookie rewriting
  265. - String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`.
  266. - Object: mapping of paths to new paths, use `"*"` to match all paths.
  267. For example, to keep one path unchanged, rewrite one path and remove other paths:
  268. ```
  269. cookiePathRewrite: {
  270. "/unchanged.path/": "/unchanged.path/",
  271. "/old.path/": "/new.path/",
  272. "*": ""
  273. }
  274. ```
  275. - **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`)
  276. - **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target
  277. - **option.timeout**: timeout (in millis) for incoming requests
  278. - **option.followRedirects**: true/false, Default: false - specify whether you want to follow redirects
  279. - **option.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
  280. - **option.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:
  281. ```
  282. 'use strict';
  283. const streamify = require('stream-array');
  284. const HttpProxy = require('http-proxy');
  285. const proxy = new HttpProxy();
  286. module.exports = (req, res, next) => {
  287. proxy.web(req, res, {
  288. target: 'http://localhost:4003/',
  289. buffer: streamify(req.rawBody)
  290. }, next);
  291. };
  292. ```
  293. ## Shorthand
  294. Use the shorthand syntax when verbose configuration is not needed. The `context` and `option.target` will be automatically configured when shorthand is used. Options can still be used if needed.
  295. ```javascript
  296. proxy('http://www.example.org:8000/api')
  297. // proxy('/api', {target: 'http://www.example.org:8000'});
  298. proxy('http://www.example.org:8000/api/books/*/**.json')
  299. // proxy('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
  300. proxy('http://www.example.org:8000/api', { changeOrigin: true })
  301. // proxy('/api', {target: 'http://www.example.org:8000', changeOrigin: true});
  302. ```
  303. ### app.use(path, proxy)
  304. If you want to use the server's `app.use` `path` parameter to match requests;
  305. Create and mount the proxy without the http-proxy-middleware `context` parameter:
  306. ```javascript
  307. app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
  308. ```
  309. `app.use` documentation:
  310. - express: http://expressjs.com/en/4x/api.html#app.use
  311. - connect: https://github.com/senchalabs/connect#mount-middleware
  312. ## WebSocket
  313. ```javascript
  314. // verbose api
  315. proxy('/', { target: 'http://echo.websocket.org', ws: true })
  316. // shorthand
  317. proxy('http://echo.websocket.org', { ws: true })
  318. // shorter shorthand
  319. proxy('ws://echo.websocket.org')
  320. ```
  321. ### External WebSocket upgrade
  322. In the previous WebSocket examples, http-proxy-middleware relies on a initial http request in order to listen to the http `upgrade` event. If you need to proxy WebSockets without the initial http request, you can subscribe to the server's http `upgrade` event manually.
  323. ```javascript
  324. var wsProxy = proxy('ws://echo.websocket.org', { changeOrigin: true })
  325. var app = express()
  326. app.use(wsProxy)
  327. var server = app.listen(3000)
  328. server.on('upgrade', wsProxy.upgrade) // <-- subscribe to http 'upgrade'
  329. ```
  330. ## Working examples
  331. View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples).
  332. - Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js))
  333. - express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js))
  334. - connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js))
  335. - WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js))
  336. ## Recipes
  337. View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases.
  338. ## Compatible servers
  339. `http-proxy-middleware` is compatible with the following servers:
  340. - [connect](https://www.npmjs.com/package/connect)
  341. - [express](https://www.npmjs.com/package/express)
  342. - [browser-sync](https://www.npmjs.com/package/browser-sync)
  343. - [lite-server](https://www.npmjs.com/package/lite-server)
  344. - [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect)
  345. - [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync)
  346. - [gulp-connect](https://www.npmjs.com/package/gulp-connect)
  347. - [gulp-webserver](https://www.npmjs.com/package/gulp-webserver)
  348. Sample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md).
  349. ## Tests
  350. Run the test suite:
  351. ```bash
  352. # install dependencies
  353. $ npm install
  354. # linting
  355. $ npm run lint
  356. # unit tests
  357. $ npm test
  358. # code coverage
  359. $ npm run cover
  360. ```
  361. ## Changelog
  362. - [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md)
  363. ## License
  364. The MIT License (MIT)
  365. Copyright (c) 2015-2018 Steven Chim