b0fec5e822b9d3becf02d071d7bd2b3178be0306922d3b4ce28ec1ed33a4610ee560ce564594382f6d338bf43feb919d79b905167b4d8511887c22917dcba4 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. # Connect
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Build Status][travis-image]][travis-url]
  5. [![Test Coverage][coveralls-image]][coveralls-url]
  6. Connect is an extensible HTTP server framework for [node](http://nodejs.org) using "plugins" known as _middleware_.
  7. ```js
  8. var connect = require('connect');
  9. var http = require('http');
  10. var app = connect();
  11. // gzip/deflate outgoing responses
  12. var compression = require('compression');
  13. app.use(compression());
  14. // store session state in browser cookie
  15. var cookieSession = require('cookie-session');
  16. app.use(cookieSession({
  17. keys: ['secret1', 'secret2']
  18. }));
  19. // parse urlencoded request bodies into req.body
  20. var bodyParser = require('body-parser');
  21. app.use(bodyParser.urlencoded({extended: false}));
  22. // respond to all requests
  23. app.use(function(req, res){
  24. res.end('Hello from Connect!\n');
  25. });
  26. //create node.js http server and listen on port
  27. http.createServer(app).listen(3000);
  28. ```
  29. ## Getting Started
  30. Connect is a simple framework to glue together various "middleware" to handle requests.
  31. ### Install Connect
  32. ```sh
  33. $ npm install connect
  34. ```
  35. ### Create an app
  36. The main component is a Connect "app". This will store all the middleware
  37. added and is, itself, a function.
  38. ```js
  39. var app = connect();
  40. ```
  41. ### Use middleware
  42. The core of Connect is "using" middleware. Middleware are added as a "stack"
  43. where incoming requests will execute each middleware one-by-one until a middleware
  44. does not call `next()` within it.
  45. ```js
  46. app.use(function middleware1(req, res, next) {
  47. // middleware 1
  48. next();
  49. });
  50. app.use(function middleware2(req, res, next) {
  51. // middleware 2
  52. next();
  53. });
  54. ```
  55. ### Mount middleware
  56. The `.use()` method also takes an optional path string that is matched against
  57. the beginning of the incoming request URL. This allows for basic routing.
  58. ```js
  59. app.use('/foo', function fooMiddleware(req, res, next) {
  60. // req.url starts with "/foo"
  61. next();
  62. });
  63. app.use('/bar', function barMiddleware(req, res, next) {
  64. // req.url starts with "/bar"
  65. next();
  66. });
  67. ```
  68. ### Error middleware
  69. There are special cases of "error-handling" middleware. There are middleware
  70. where the function takes exactly 4 arguments. When a middleware passes an error
  71. to `next`, the app will proceed to look for the error middleware that was declared
  72. after that middleware and invoke it, skipping any error middleware above that
  73. middleware and any non-error middleware below.
  74. ```js
  75. // regular middleware
  76. app.use(function (req, res, next) {
  77. // i had an error
  78. next(new Error('boom!'));
  79. });
  80. // error middleware for errors that occurred in middleware
  81. // declared before this
  82. app.use(function onerror(err, req, res, next) {
  83. // an error occurred!
  84. });
  85. ```
  86. ### Create a server from the app
  87. The last step is to actually use the Connect app in a server. The `.listen()` method
  88. is a convenience to start a HTTP server (and is identical to the `http.Server`'s `listen`
  89. method in the version of Node.js you are running).
  90. ```js
  91. var server = app.listen(port);
  92. ```
  93. The app itself is really just a function with three arguments, so it can also be handed
  94. to `.createServer()` in Node.js.
  95. ```js
  96. var server = http.createServer(app);
  97. ```
  98. ## Middleware
  99. These middleware and libraries are officially supported by the Connect/Express team:
  100. - [body-parser](https://www.npmjs.com/package/body-parser) - previous `bodyParser`, `json`, and `urlencoded`. You may also be interested in:
  101. - [body](https://www.npmjs.com/package/body)
  102. - [co-body](https://www.npmjs.com/package/co-body)
  103. - [raw-body](https://www.npmjs.com/package/raw-body)
  104. - [compression](https://www.npmjs.com/package/compression) - previously `compress`
  105. - [connect-timeout](https://www.npmjs.com/package/connect-timeout) - previously `timeout`
  106. - [cookie-parser](https://www.npmjs.com/package/cookie-parser) - previously `cookieParser`
  107. - [cookie-session](https://www.npmjs.com/package/cookie-session) - previously `cookieSession`
  108. - [csurf](https://www.npmjs.com/package/csurf) - previously `csrf`
  109. - [errorhandler](https://www.npmjs.com/package/errorhandler) - previously `error-handler`
  110. - [express-session](https://www.npmjs.com/package/express-session) - previously `session`
  111. - [method-override](https://www.npmjs.com/package/method-override) - previously `method-override`
  112. - [morgan](https://www.npmjs.com/package/morgan) - previously `logger`
  113. - [response-time](https://www.npmjs.com/package/response-time) - previously `response-time`
  114. - [serve-favicon](https://www.npmjs.com/package/serve-favicon) - previously `favicon`
  115. - [serve-index](https://www.npmjs.com/package/serve-index) - previously `directory`
  116. - [serve-static](https://www.npmjs.com/package/serve-static) - previously `static`
  117. - [vhost](https://www.npmjs.com/package/vhost) - previously `vhost`
  118. Most of these are exact ports of their Connect 2.x equivalents. The primary exception is `cookie-session`.
  119. Some middleware previously included with Connect are no longer supported by the Connect/Express team, are replaced by an alternative module, or should be superseded by a better module. Use one of these alternatives instead:
  120. - `cookieParser`
  121. - [cookies](https://www.npmjs.com/package/cookies) and [keygrip](https://www.npmjs.com/package/keygrip)
  122. - `limit`
  123. - [raw-body](https://www.npmjs.com/package/raw-body)
  124. - `multipart`
  125. - [connect-multiparty](https://www.npmjs.com/package/connect-multiparty)
  126. - [connect-busboy](https://www.npmjs.com/package/connect-busboy)
  127. - `query`
  128. - [qs](https://www.npmjs.com/package/qs)
  129. - `staticCache`
  130. - [st](https://www.npmjs.com/package/st)
  131. - [connect-static](https://www.npmjs.com/package/connect-static)
  132. Checkout [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) for many other compatible middleware!
  133. ## API
  134. The Connect API is very minimalist, enough to create an app and add a chain
  135. of middleware.
  136. When the `connect` module is required, a function is returned that will construct
  137. a new app when called.
  138. ```js
  139. // require module
  140. var connect = require('connect')
  141. // create app
  142. var app = connect()
  143. ```
  144. ### app(req, res[, next])
  145. The `app` itself is a function. This is just an alias to `app.handle`.
  146. ### app.handle(req, res[, out])
  147. Calling the function will run the middleware stack against the given Node.js
  148. http request (`req`) and response (`res`) objects. An optional function `out`
  149. can be provided that will be called if the request (or error) was not handled
  150. by the middleware stack.
  151. ### app.listen([...])
  152. Start the app listening for requests. This method will internally create a Node.js
  153. HTTP server and call `.listen()` on it.
  154. This is an alias to the `server.listen()` method in the version of Node.js running,
  155. so consult the Node.js documentation for all the different variations. The most
  156. common signature is [`app.listen(port)`](https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_server_listen_port_hostname_backlog_callback).
  157. ### app.use(fn)
  158. Use a function on the app, where the function represents a middleware. The function
  159. will be invoked for every request in the order that `app.use` is called. The function
  160. is called with three arguments:
  161. ```js
  162. app.use(function (req, res, next) {
  163. // req is the Node.js http request object
  164. // res is the Node.js http response object
  165. // next is a function to call to invoke the next middleware
  166. })
  167. ```
  168. In addition to a plan function, the `fn` argument can also be a Node.js HTTP server
  169. instance or another Connect app instance.
  170. ### app.use(route, fn)
  171. Use a function on the app, where the function represents a middleware. The function
  172. will be invoked for every request in which the URL (`req.url` property) starts with
  173. the given `route` string in the order that `app.use` is called. The function is
  174. called with three arguments:
  175. ```js
  176. app.use('/foo', function (req, res, next) {
  177. // req is the Node.js http request object
  178. // res is the Node.js http response object
  179. // next is a function to call to invoke the next middleware
  180. })
  181. ```
  182. In addition to a plan function, the `fn` argument can also be a Node.js HTTP server
  183. instance or another Connect app instance.
  184. The `route` is always terminated at a path separator (`/`) or a dot (`.`) character.
  185. This means the given routes `/foo/` and `/foo` are the same and both will match requests
  186. with the URLs `/foo`, `/foo/`, `/foo/bar`, and `/foo.bar`, but not match a request with
  187. the URL `/foobar`.
  188. The `route` is matched in a case-insensitive manor.
  189. In order to make middleware easier to write to be agnostic of the `route`, when the
  190. `fn` is invoked, the `req.url` will be altered to remove the `route` part (and the
  191. original will be available as `req.originalUrl`). For example, if `fn` is used at the
  192. route `/foo`, the request for `/foo/bar` will invoke `fn` with `req.url === '/bar'`
  193. and `req.originalUrl === '/foo/bar'`.
  194. ## Running Tests
  195. ```bash
  196. npm install
  197. npm test
  198. ```
  199. ## People
  200. The Connect project would not be the same without all the people involved.
  201. The original author of Connect is [TJ Holowaychuk](https://github.com/tj)
  202. The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson)
  203. [List of all contributors](https://github.com/senchalabs/connect/graphs/contributors)
  204. ## Node Compatibility
  205. - Connect `< 1.x` - node `0.2`
  206. - Connect `1.x` - node `0.4`
  207. - Connect `< 2.8` - node `0.6`
  208. - Connect `>= 2.8 < 3` - node `0.8`
  209. - Connect `>= 3` - node `0.10`, `0.12`, `4.x`, `5.x`, `6.x`, `7.x`, `8.x`; io.js `1.x`, `2.x`, `3.x`
  210. ## License
  211. [MIT](LICENSE)
  212. [npm-image]: https://img.shields.io/npm/v/connect.svg
  213. [npm-url]: https://npmjs.org/package/connect
  214. [travis-image]: https://img.shields.io/travis/senchalabs/connect/master.svg
  215. [travis-url]: https://travis-ci.org/senchalabs/connect
  216. [coveralls-image]: https://img.shields.io/coveralls/senchalabs/connect/master.svg
  217. [coveralls-url]: https://coveralls.io/r/senchalabs/connect
  218. [downloads-image]: https://img.shields.io/npm/dm/connect.svg
  219. [downloads-url]: https://npmjs.org/package/connect