项目原始demo,不改动
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
Este repositório está arquivado. Você pode visualizar os arquivos e realizar clone, mas não poderá realizar push nem abrir issues e pull requests.

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