Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,424 lines · 49.6 KiB · Markdown

Last changed by

Fixed options.filename, exposing to template enginesTj Holowaychukbefore adoption93189ad

History of this file

Take it

The walk stopped after 200 commits: lines older than 41266aa point at it.

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1–4why, one step back
1### Installation
23 $ npm install express4

added quick start to guideTj Holowaychukbefore adoption723774a

lines 5–25why, one step back
5or to access the `express(1)` executable install globally:
67 $ npm install -g express89## Quick Start1011 The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below:1213 Create the app:1415 $ npm install -g express16 $ express /tmp/foo && cd /tmp/foo1718 Install dependencies:1920 $ npm install -d2122 Start the server:2324 $ node app.js25

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 26–73why, one step back
26### Creating A Server
2728 To create an instance of the _express.HTTPServer_, simply invoke the _createServer()_ method. With our instance _app_ we can then define routes based on the HTTP verbs, in this example _app.get()_.2930 var app = require('express').createServer();31 32 app.get('/', function(req, res){33 res.send('hello world');34 });35 36 app.listen(3000);3738### Creating An HTTPS Server3940 To initialize a _express.HTTPSServer_ we do the same as above, however we41 pass an options object, accepting _key_, _cert_ and the others mentioned in node's [https documentation](http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer).42 43 var app = require('express').createServer({ key: ... });4445### Configuration4647Express supports arbitrary environments, such as _production_ and _development_. Developers48can use the _configure()_ method to setup needs required by the current environment. When49_configure()_ is called without an environment name it will be run in _every_ environment 50prior to the environment specific callback.5152In the example below we only _dumpExceptions_, and respond with exception stack traces53in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.54Note the use of _app.router_, which can (optionally) be used to mount the application routes,55otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.5657 app.configure(function(){58 app.use(express.methodOverride());59 app.use(express.bodyParser());60 app.use(app.router);61 });62 63 app.configure('development', function(){64 app.use(express.static(__dirname + '/public'));65 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));66 });67 68 app.configure('production', function(){69 var oneYear = 31557600000;70 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));71 app.use(express.errorHandler());72 });73

docs for multiple envs in app.configure() callsTj Holowaychukbefore adoption45d149c

lines 74–79why, one step back
74For similar environments you may also pass several env strings:
7576 app.configure('stage', 'prod', function(){77 // config78 });79

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 80–110why, one step back
80For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:
8182 app.configure(function(){83 app.set('views', __dirname + '/views');84 app.set('views');85 // => "/absolute/path/to/views"86 87 app.enable('some feature');88 // same as app.set('some feature', true);89 90 app.disable('some feature');91 // same as app.set('some feature', false);92 93 app.enabled('some feature')94 // => false95 });9697To alter the environment we can set the _NODE_ENV_ environment variable, for example:9899 $ NODE_ENV=production node app.js100101This is _very_ important, as many caching mechanisms are _only enabled_ when in production.102103### Settings104105Express supports the following settings out of the box:106107 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.108 * _views_ Root views directory defaulting to **CWD/views**109 * _view engine_ Default view engine name for views rendered without extensions110 * _view options_ An object specifying global view options

docs for "view cache" settingTj Holowaychukbefore adoption805b9ac

line 111why, one step back
111 * _view cache_ Enable view caching (enabled in production)

Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd

line 112why, one step back
112 * _case sensitive routes_ Enable case-sensitive routing

Added "strict routing" setting for trailing slashesTj Holowaychukbefore adoption6f7075b

line 113why, one step back
113 * _strict routing_ When enabled trailing slashes are no longer ignored

moved jsonp testsTj Holowaychukbefore adoption87bc265

line 114why, one step back
114 * _jsonp callback_ Enable _res.send()_ / _res.json()_ transparent jsonp support

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 115–197why, one step back
115
116### Routing117118Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.119For example we may want to render a user's account for the path _/user/12_, this120can be done by defining the route below. The values associated to the named placeholders 121are available as `req.params`.122123 app.get('/user/:id', function(req, res){124 res.send('user ' + req.params.id);125 });126127A route is simple a string which is compiled to a _RegExp_ internally. For example128when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:129130 \/user\/([^\/]+)\/?131132Regular expression literals may also be passed for complex uses. Since capture133groups with literal _RegExp_'s are anonymous we can access them directly `req.params`. So our first capture group would be _req.params[0]_ and the second would follow as _req.params[1]_.134135 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){136 res.send(req.params);137 });138139Curl requests against the previously defined route:140141 $ curl http://dev:3000/user142 [null,null]143 $ curl http://dev:3000/users144 [null,null]145 $ curl http://dev:3000/users/1146 ["1",null]147 $ curl http://dev:3000/users/1..15148 ["1","15"]149150Below are some route examples, and the associated paths that they151may consume:152153 "/user/:id"154 /user/12155156 "/users/:id?"157 /users/5158 /users159160 "/files/*"161 /files/jquery.js162 /files/javascripts/jquery.js163164 "/file/*.*"165 /files/jquery.js166 /files/javascripts/jquery.js167 168 "/user/:id/:operation?"169 /user/1170 /user/1/edit171 172 "/products.:format"173 /products.json174 /products.xml175176 "/products.:format?"177 /products.json178 /products.xml179 /products180 181 "/user/:id.:format?"182 /user/12183 /user/12.json184185For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:186187 var express = require('express')188 , app = express.createServer();189190 app.use(express.bodyParser());191192 app.post('/', function(req, res){193 res.send(req.body);194 });195196 app.listen(3000);197

docsTj Holowaychukbefore adoption6106188

line 198why, one step back
198Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use _'/user/:id([0-9]+)'_ which will _not_ match unless the placeholder value contains only digits.

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 199–266why, one step back
199
200### Passing Route Control201202We may pass control to the next _matching_ route, by calling the _third_ argument,203the _next()_ function. When a match cannot be made, control is passed back to Connect,204and middleware continue to be invoked in the order that they are added via _use()_. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_ and decides to respond.205206 app.get('/users/:id?', function(req, res, next){207 var id = req.params.id;208 if (id) {209 // do something210 } else {211 next();212 }213 });214 215 app.get('/users', function(req, res){216 // do something else217 });218219The _app.all()_ method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to _req.user_.220221 var express = require('express')222 , app = express.createServer();223224 var users = [{ name: 'tj' }];225226 app.all('/user/:id/:op?', function(req, res, next){227 req.user = users[req.params.id];228 if (req.user) {229 next();230 } else {231 next(new Error('cannot find user ' + req.params.id));232 }233 });234235 app.get('/user/:id', function(req, res){236 res.send('viewing ' + req.user.name);237 });238239 app.get('/user/:id/edit', function(req, res){240 res.send('editing ' + req.user.name);241 });242243 app.put('/user/:id', function(req, res){244 res.send('updating ' + req.user.name);245 });246247 app.get('*', function(req, res){248 res.send('what???', 404);249 });250251 app.listen(3000); 252253### Middleware254255Middleware via [Connect](http://github.com/senchalabs/connect) can be256passed to _express.createServer()_ as you would with a regular Connect server. For example:257258 var express = require('express');259260 var app = express.createServer(261 express.logger()262 , express.bodyParser()263 );264265Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.266

Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa

line 267why, one step back
267 app.use(express.logger({ format: ':method :url' }));

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 268–279why, one step back
268
269Typically with connect middleware you would _require('connect')_ like so:270271 var connect = require('connect');272 app.use(connect.logger());273 app.use(connect.bodyParser());274275This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:276277 app.use(express.logger());278 app.use(express.bodyParser());279

added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167

lines 280–306why, one step back
280Middleware ordering is important, when Connect receives a request the _first_ middleware we pass to _createServer()_ or _use()_ is executed with three parameters, _request_, _response_, and a callback function usually named _next_. When _next()_ is invoked the second middleware will then have it's turn and so on. This is important to note because many middleware depend on each other, for example _methodOverride()_ checks _req.body._method_ for the HTTP method override, however _bodyParser()_ parses the request body and populates _req.body_. Another example of this is cookie parsing and session support, we must first _use()_ _cookieParser()_ followed by _session()_.
281282Many Express applications may contain the line _app.use(app.router)_, while this may appear strange, it's simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the _last_ middleware so that any exception passed to _next()_ will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below283284 app.use(express.logger(...));285 app.use(express.bodyParser(...));286 app.use(express.cookieParser(...));287 app.use(express.session(...));288 app.use(app.router);289 app.use(express.static(...));290 app.use(express.errorHandler(...));291292First we add _logger()_ so that it may wrap node's _req.end()_ method, providing us with response-time data. Next the request's body will be parsed (if any), followed by cookie parsing and session support, meaning _req.session_ will be defined by the time we hit our routes in _app.router_. If a request such as _GET /javascripts/jquery.js_ is handled by our routes, and we do not call _next()_ then the _static()_ middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.293294 var downloads = {};295296 app.use(app.router);297 app.use(express.static(__dirname + '/public'));298299 app.get('/*', function(req, res, next){300 var file = req.params[0];301 downloads[file] = downloads[file] || 0;302 downloads[file]++;303 next();304 });305306

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 307–377why, one step back
307### Route Middleware
308309Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.310311Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 312313 app.get('/user/:id', function(req, res, next){314 loadUser(req.params.id, function(err, user){315 if (err) return next(err);316 res.send('Viewing user ' + user.name);317 });318 });319320To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 321322 function loadUser(req, res, next) {323 // You would fetch your user from the db324 var user = users[req.params.id];325 if (user) {326 req.user = user;327 next();328 } else {329 next(new Error('Failed to load user ' + req.params.id));330 }331 }332 333 app.get('/user/:id', loadUser, function(req, res){334 res.send('Viewing user ' + req.user.name);335 });336337Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.338339 function andRestrictToSelf(req, res, next) {340 req.authenticatedUser.id == req.user.id341 ? next()342 : next(new Error('Unauthorized'));343 }344 345 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){346 res.send('Editing user ' + req.user.name);347 });348349Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.350351 function andRestrictTo(role) {352 return function(req, res, next) {353 req.authenticatedUser.role == role354 ? next()355 : next(new Error('Unauthorized'));356 }357 }358 359 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){360 res.send('Deleted user ' + req.user.name);361 });362363Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.364365 var a = [middleware1, middleware2]366 , b = [middleware3, middleware4]367 , all = [a, b];368 369 app.get('/foo', a, function(){});370 app.get('/bar', a, function(){});371 372 app.get('/', a, middleware3, middleware4, function(){});373 app.get('/', a, b, function(){});374 app.get('/', all, function(){});375376For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.377

docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302

lines 378–379why, one step back
378There are times when we may want to "skip" passed remaining route middleware, but continue matching subsequent routes. To do this we invoke `next()` with the string "route" `next('route')`. If no remaining routes match the request url then Express will respond with 404 Not Found.
379

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 380–625why, one step back
380### HTTP Methods
381382We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.383384 A common example for _POST_ usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.385 386 <form method="post" action="/">387 <input type="text" name="user[name]" />388 <input type="text" name="user[email]" />389 <input type="submit" value="Submit" />390 </form>391392By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:393394 app.use(express.bodyParser());395396Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.397398 app.post('/', function(req, res){399 console.log(req.body.user);400 res.redirect('back');401 });402403When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.404405 app.use(express.bodyParser());406 app.use(express.methodOverride());407408The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:409410 <form method="post" action="/">411 <input type="hidden" name="_method" value="put" />412 <input type="text" name="user[name]" />413 <input type="text" name="user[email]" />414 <input type="submit" value="Submit" /> 415 </form>416417 app.put('/', function(){418 console.log(req.body.user);419 res.redirect('back');420 });421422### Error Handling423424Express provides the _app.error()_ method which receives exceptions thrown within a route,425or passed to _next(err)_. Below is an example which serves different pages based on our426ad-hoc _NotFound_ exception:427428 function NotFound(msg){429 this.name = 'NotFound';430 Error.call(this, msg);431 Error.captureStackTrace(this, arguments.callee);432 }433 434 NotFound.prototype.__proto__ = Error.prototype;435 436 app.get('/404', function(req, res){437 throw new NotFound;438 });439 440 app.get('/500', function(req, res){441 throw new Error('keyboard cat!');442 });443444We can call _app.error()_ several times as shown below.445Here we check for an instanceof _NotFound_ and show the446404 page, or we pass on to the next error handler.447448Note that these handlers can be defined anywhere, as they449will be placed below the route handlers on _listen()_. This 450allows for definition within _configure()_ blocks so we can451handle exceptions in different ways based on the environment.452453 app.error(function(err, req, res, next){454 if (err instanceof NotFound) {455 res.render('404.jade');456 } else {457 next(err);458 }459 });460461Here we assume all errors as 500 for the simplicity of462this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.463464 app.error(function(err, req, res){465 res.render('500.jade', {466 error: err467 });468 });469470Our apps could also utilize the Connect _errorHandler_ middleware471to report on exceptions. For example if we wish to output exceptions 472in "development" mode to _stderr_ we can use:473474 app.use(express.errorHandler({ dumpExceptions: true }));475476Also during development we may want fancy html pages to show exceptions477that are passed or thrown, so we can set _showStack_ to true:478479 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));480481The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_482is present, which is useful for developing apps that rely heavily on client-side JavaScript.483484### Route Param Pre-conditions485486Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_, we might typically do something like below:487488 app.get('/user/:userId', function(req, res, next){489 User.get(req.params.userId, function(err, user){490 if (err) return next(err);491 res.send('user ' + user.name);492 });493 }); 494495With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.496497 app.param('userId', function(req, res, next, id){498 User.get(id, function(err, user){499 if (err) return next(err);500 if (!user) return next(new Error('failed to find user'));501 req.user = user;502 next();503 });504 });505506Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:507508 app.get('/user/:userId', function(req, res){509 res.send('user ' + req.user.name);510 });511512### View Rendering513514View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name515of the module that will be required. For example the view _layout.ejs_ will516tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour517_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.518519Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,520and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 521the _body_ local variable in _layout.jade_.522523 app.get('/', function(req, res){524 res.render('index.jade', { title: 'My Site' });525 });526527The new _view engine_ setting allows us to specify our default template engine,528so for example when using jade we could set:529530 app.set('view engine', 'jade');531532Allowing us to render with:533534 res.render('index');535536vs:537538 res.render('index.jade');539540When _view engine_ is set, extensions are entirely optional, however we can still541mix and match template engines:542543 res.render('another-page.ejs');544545Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:546547 app.set('view options', {548 layout: false549 });550551Which can then be overridden within the _res.render()_ call if need be:552553 res.render('myview.ejs', { layout: true });554555When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:556557 res.render('page', { layout: 'mylayout' });558559Otherwise we must specify the extension:560561 res.render('page', { layout: 'mylayout.jade' });562563These paths may also be absolute:564565 res.render('page', { layout: __dirname + '/../../mylayout.jade' });566567A good example of this is specifying custom _ejs_ opening and closing tags:568569 app.set('view options', {570 open: '{{',571 close: '}}'572 });573574### View Partials575576The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating577in a view to display comments, we could use partial collection:578579 partial('comment', { collection: comments });580581If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:582583 partial('comment', comments);584585When using the partial collection support a few "magic" locals are provided586for free:587588 * _firstInCollection_ true if this is the first object589 * _indexInCollection_ index of the object in the collection590 * _lastInCollection_ true if this is the last object591 * _collectionLength_ length of the collection592593Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with _partial('blog/post', post)_ it would generate the _post_ local, but the view calling this function had the local _user_, it would be available to the _blog/post_ view as well.594595For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).596597__NOTE:__ be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.598599### View Lookup600601View lookup is performed relative to the parent view, for example if we had a page view named _views/user/list.jade_, and within that view we did _partial('edit')_ it would attempt to load _views/user/edit.jade_, whereas _partial('../messages')_ would load _views/messages.jade_.602603The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have _res.render('users')_ either _views/users.jade_, or _views/users/index.jade_.604605When utilizing index views as shown above, we may reference _views/users/index.jade_ from a view in the same directory by _partial('users')_, and the view system will try _../users/index_, preventing us from needing to call _partial('index')_.606607### Template Engines608609Below are a few template engines commonly used with Express:610611 * [Haml](http://github.com/visionmedia/haml.js) haml implementation612 * [Jade](http://jade-lang.com) haml.js successor613 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript614 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating615 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node616617### Session Support618619Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.620621 app.use(express.cookieParser());622 app.use(express.session({ secret: "keyboard cat" }));623624By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:625

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4

line 626why, one step back
626 var RedisStore = require('connect-redis')(express);

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 627–631why, one step back
627 app.use(express.cookieParser());
628 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));629630Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:631

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4

line 632why, one step back
632 var RedisStore = require('connect-redis')(express);

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 633–763why, one step back
633 app.use(express.bodyParser());
634 app.use(express.cookieParser());635 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));636637 app.post('/add-to-cart', function(req, res){638 // Perhaps we posted several items with a form639 // (use the bodyParser() middleware for this)640 var items = req.body.items;641 req.session.items = items;642 res.redirect('back');643 });644645 app.get('/add-to-cart', function(req, res){646 // When redirected back to GET /add-to-cart647 // we could check req.session.items && req.session.items.length648 // to print out a message649 if (req.session.items && req.session.items.length) {650 req.flash('info', 'You have %s items in your cart', req.session.items.length);651 }652 res.render('shopping-cart');653 });654655The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/middleware-session.html) documentation.656657### Migration Guide658659 Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.660661### req.header(key[, defaultValue])662663Get the case-insensitive request header _key_, with optional _defaultValue_:664665 req.header('Host');666 req.header('host');667 req.header('Accept', '*/*');668669The _Referrer_ and _Referer_ header fields are special-cased, either will work:670671 // sent Referrer: http://google.com672673 req.header('Referer');674 // => "http://google.com"675676 req.header('Referrer');677 // => "http://google.com"678679### req.accepts(type)680681Check if the _Accept_ header is present, and includes the given _type_.682683When the _Accept_ header is not present _true_ is returned. Otherwise684the given _type_ is matched by an exact match, and then subtypes. You685may pass the subtype such as "html" which is then converted internally686to "text/html" using the mime lookup table.687688 // Accept: text/html689 req.accepts('html');690 // => true691692 // Accept: text/*; application/json693 req.accepts('html');694 req.accepts('text/html');695 req.accepts('text/plain');696 req.accepts('application/json');697 // => true698699 req.accepts('image/png');700 req.accepts('png');701 // => false702703### req.is(type)704705Check if the incoming request contains the _Content-Type_706header field, and it contains the give mime _type_.707 708 // With Content-Type: text/html; charset=utf-8709 req.is('html');710 req.is('text/html');711 // => true712 713 // When Content-Type is application/json714 req.is('json');715 req.is('application/json');716 // => true717 718 req.is('html');719 // => false720 721Ad-hoc callbacks can also be registered with Express, to perform722assertions again the request, for example if we need an expressive723way to check if our incoming request is an image, we can register _"an image"_724callback:725 726 app.is('an image', function(req){727 return 0 == req.headers['content-type'].indexOf('image');728 });729 730Now within our route callbacks, we can use to to assert content types731such as _"image/jpeg"_, _"image/png"_, etc.732 733 app.post('/image/upload', function(req, res, next){734 if (req.is('an image')) {735 // do something736 } else {737 next();738 }739 });740741Keep in mind this method is _not_ limited to checking _Content-Type_, you742can perform any request assertion you wish.743744Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:745746 req.is('image/*');747748We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.749750 req.is('*/json');751752### req.param(name[, default])753754Return the value of param _name_ when present or _default_.755756 - Checks route params (_req.params_), ex: /user/:id757 - Checks query string params (_req.query_), ex: ?id=12758 - Checks urlencoded body params (_req.body_), ex: id=12759760To utilize urlencoded request bodies, _req.body_761should be an object. This can be done by using762the _express.bodyParser middleware.763

docs for req.get()Tj Holowaychukbefore adoption6bb100d

lines 764–774why, one step back
764### req.get(field, param)
765766 Get _field_'s _param_ value, defaulting to '' when the _param_767 or _field_ is not present.768769 req.get('content-disposition', 'filename');770 // => "something.png"771772 req.get('Content-Type', 'boundary');773 // => "--foo-bar-baz"774

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 775–880why, one step back
775### req.flash(type[, msg])
776777Queue flash _msg_ of the given _type_.778779 req.flash('info', 'email sent');780 req.flash('error', 'email delivery failed');781 req.flash('info', 'email re-sent');782 // => 2783784 req.flash('info');785 // => ['email sent', 'email re-sent']786787 req.flash('info');788 // => []789790 req.flash();791 // => { error: ['email delivery failed'], info: [] }792793Flash notification message may also utilize formatters, by default only the %s string formatter is available:794795 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);796797### req.isXMLHttpRequest798799Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header800to see if it was issued by an _XMLHttpRequest_:801802 req.xhr803 req.isXMLHttpRequest804805### res.header(key[, val])806807Get or set the response header _key_.808809 res.header('Content-Length');810 // => undefined811812 res.header('Content-Length', 123);813 // => 123814 815 res.header('Content-Length');816 // => 123817818### res.charset819820Sets the charset for subsequent `Content-Type` header fields. For example `res.send()` and `res.render()` default to "utf8", so we may explicitly set the charset before rendering a template:821822 res.charset = 'ISO-8859-1';823 res.render('users');824825or before responding with `res.send()`:826827 res.charset = 'ISO-8859-1';828 res.send(str);829830or with node's `res.end()`:831832 res.charset = 'ISO-8859-1';833 res.header('Content-Type', 'text/plain');834 res.end(str);835836### res.contentType(type)837838Sets the _Content-Type_ response header to the given _type_.839840 var filename = 'path/to/image.png';841 res.contentType(filename);842 // Content-Type is now "image/png"843844A literal _Content-Type_ works as well:845846 res.contentType('application/json');847848Or simply the extension without leading `.`:849850 res.contentType('json');851852### res.attachment([filename])853854Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.855856 res.attachment('path/to/my/image.png');857858### res.sendfile(path[, options[, callback]])859860Used by `res.download()` to transfer an arbitrary file. 861862 res.sendfile('path/to/my.file');863864This method accepts an optional callback which is called when865an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.866867 res.sendfile(path, function(err){868 if (err) {869 next(err);870 } else {871 console.log('transferred %s', path);872 }873 });874875Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:876877 res.sendfile(path, { bufferSize: 1024 }, function(err){878 // handle879 });880

docsTj Holowaychukbefore adoption236a412

line 881why, one step back
881### res.download(file[, filename[, callback[, callback2]]])

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 882–892why, one step back
882
883Transfer the given _file_ as an attachment with optional alternative _filename_.884885 res.download('path/to/image.png');886 res.download('path/to/image.png', 'foo.png');887888This is equivalent to:889890 res.attachment(file);891 res.sendfile(file);892

docsTj Holowaychukbefore adoption236a412

line 893why, one step back
893An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_. Within this callback you may still respond, as the header has not been sent.

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 894–896why, one step back
894
895 res.download(path, 'expenses.doc', function(err){896 // handle

docsTj Holowaychukbefore adoption236a412

lines 897–904why, one step back
897 });
898899An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.900901 res.download(path, function(err){902 // error or finished903 }, function(err){904 // connection related error

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 905–925why, one step back
905 });
906907### res.send(body|status[, headers|status[, status]])908909The _res.send()_ method is a high level response utility allowing you to pass910objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:911912 res.send(); // 204913 res.send(new Buffer('wahoo'));914 res.send({ some: 'json' });915 res.send('<p>some html</p>');916 res.send('Sorry, cant find that', 404);917 res.send('text', { 'Content-Type': 'text/plain' }, 201);918 res.send(404);919920By default the _Content-Type_ response header is set, however if explicitly921assigned through `res.send()` or previously with `res.header()` or `res.contentType()`922it will not be set again.923924Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.925

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 926–937why, one step back
926### res.json(obj[, headers|status[, status]])
927928 Send a JSON response with optional _headers_ and _status_. This method929 is ideal for JSON-only APIs, however _res.send(obj)_ will send JSON as930 well, though not ideal for cases when you want to send for example a string931 as JSON, since the default for _res.send(string)_ is text/html.932933 res.json(null);934 res.json({ user: 'tj' });935 res.json('oh noes!', 500);936 res.json('I dont have that', 404);937

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 938–953why, one step back
938### res.redirect(url[, status])
939940Redirect to the given _url_ with a default response _status_ of 302.941942 res.redirect('/', 301);943 res.redirect('/account');944 res.redirect('http://google.com');945 res.redirect('home');946 res.redirect('back');947948Express supports "redirect mapping", which by default provides _home_, and _back_.949The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes950the "home" setting and defaults to "/".951952### res.cookie(name, val[, options])953

docsTj Holowaychukbefore adoption6815feb

lines 954–955why, one step back
954Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc. The _path_ option defaults to the app's "home" setting, which
955is typically "/".

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 956–971why, one step back
956
957 // "Remember me" for 15 minutes 958 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });959960The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:961962 res.cookie('rememberme', 'yes', { maxAge: 900000 });963964To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:965966 app.use(express.cookieParser());967 968 app.get('/', function(req, res){969 // use req.cookies.rememberme970 });971

Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d

line 972why, one step back
972### res.clearCookie(name[, options])

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

line 973why, one step back
973

docsTj Holowaychukbefore adoption6815feb

lines 974–975why, one step back
974Clear cookie _name_ by setting "expires" far in the past. Much like
975_res.cookie()_ the _path_ option also defaults to the "home" setting.

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 976–989why, one step back
976
977 res.clearCookie('rememberme');978979### res.render(view[, options[, fn]])980981Render _view_ with the given _options_ and optional callback _fn_.982When a callback function is given a response will _not_ be made983automatically, however otherwise a response of _200_ and _text/html_ is given.984985The _options_ passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:986987 var user = { name: 'tj' };988 res.render('index', { layout: false, user: user });989

Added docs for `status` option special-case. Closes #739Tj Holowaychukbefore adoptionc0aab36

lines 990–998why, one step back
990This _options_ object is also considered an "options" object. For example
991when you pass the _status_ local, it's not only available to the view, it992sets the response status to this number. This is also useful if a template993engine accepts specific options, such as _debug_, or _compress_. Below994is an example of how one might render an error page, passing the _status_ for995display, as well as it setting _res.statusCode_.996997 res.render('error', { status: 500, message: 'Internal Server Error' });998

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 999–1239why, one step back
999### res.partial(view[, options])
10001001Render _view_ partial with the given _options_. This method is always available1002to the view as a local variable.10031004- _object_ the object named by _as_ or derived from the view name1005- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.1006 * as: 'something' will add the _something_ local variable1007 * as: this will use the collection value as the template context1008 * as: global will merge the collection value's properties with _locals_10091010- _collection_ Array of objects, the name is derived from the view name itself. 1011 For example _video.html_ will have a object _video_ available to it.10121013The following are equivalent, and the name of collection value when passed1014to the partial will be _movie_ as derived from the name.10151016 partial('theatre/movie.jade', { collection: movies });1017 partial('theatre/movie.jade', movies);1018 partial('movie.jade', { collection: movies });1019 partial('movie.jade', movies);1020 partial('movie', movies);1021 // In view: movie.director10221023To change the local from _movie_ to _video_ we can use the "as" option:10241025 partial('movie', { collection: movies, as: 'video' });1026 // In view: video.director10271028Also we can make our movie the value of _this_ within our view so that instead1029of _movie.director_ we could use _this.director_.10301031 partial('movie', { collection: movies, as: this });1032 // In view: this.director10331034Another alternative is to "expand" the properties of the collection item into1035pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:10361037 partial('movie', { collection: movies, as: global });1038 // In view: director10391040This same logic applies to a single partial object usage:10411042 partial('movie', { object: movie, as: this });1043 // In view: this.director10441045 partial('movie', { object: movie, as: global });1046 // In view: director10471048 partial('movie', { object: movie, as: 'video' });1049 // In view: video.director10501051 partial('movie', { object: movie });1052 // In view: movie.director10531054When a non-collection (does _not_ have _.length_) is passed as the second argument, it is assumed to be the _object_, after which the object's local variable name is derived from the view name:10551056 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1057 partial('movie', movie)1058 // => In view: movie.director10591060The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:10611062 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1063 partial('movie', movie)10641065For cases like this where passing a plain object is desired, simply assign it to a key, or use the `object` key which will use the filename-derived variable name. The examples below are equivalent:10661067 partial('movie', { locals: { movie: movie }})1068 partial('movie', { movie: movie })1069 partial('movie', { object: movie })10701071This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:10721073 app.get('/users', function(req, res){1074 if (req.xhr) {1075 // respond with the each user in the collection1076 // passed to the "user" view1077 res.partial('user', users);1078 } else {1079 // respond with layout, and users page1080 // which internally does partial('user', users)1081 // along with other UI1082 res.render('users', { users: users });1083 }1084 });10851086### res.local(name[, val])10871088Get or set the given local variable _name_. The locals built up for a response are applied to those given to the view rendering methods such as `res.render()`.10891090 app.all('/movie/:id', function(req, res, next){1091 Movie.get(req.params.id, function(err, movie){1092 // Assigns res.locals.movie = movie1093 res.local('movie', movie);1094 });1095 });1096 1097 app.get('/movie/:id', function(req, res){1098 // movie is already a local, however we1099 // can pass more if we wish1100 res.render('movie', { displayReviews: true });1101 });11021103### res.locals(obj)11041105 Assign several locals with the given _obj_. The following are equivalent:1106 1107 res.local('foo', bar);1108 res.local('bar', baz);11091110 res.locals({ foo: bar, bar, baz });11111112### app.set(name[, val])11131114Apply an application level setting _name_ to _val_, or1115get the value of _name_ when _val_ is not present:11161117 app.set('views', __dirname + '/views');1118 app.set('views');1119 // => ...path...11201121Alternatively you may simply access the settings via _app.settings_:11221123 app.settings.views1124 // => ...path...11251126### app.enable(name)11271128Enable the given setting _name_:11291130 app.enable('some arbitrary setting');1131 app.set('some arbitrary setting');1132 // => true11331134 app.enabled('some arbitrary setting');1135 // => true11361137### app.enabled(name)11381139Check if setting _name_ is enabled:11401141 app.enabled('view cache');1142 // => false11431144 app.enable('view cache');1145 app.enabled('view cache');1146 // => true11471148### app.disable(name)11491150Disable the given setting _name_:11511152 app.disable('some setting');1153 app.set('some setting');1154 // => false1155 1156 app.disabled('some setting');1157 // => false11581159### app.disabled(name)11601161Check if setting _name_ is disabled:11621163 app.enable('view cache');11641165 app.disabled('view cache');1166 // => false11671168 app.disable('view cache');1169 app.disabled('view cache');1170 // => true11711172### app.configure(env|function[, function])11731174Define a callback function for the given _env_ (or all environments) with callback _function_:11751176 app.configure(function(){1177 // executed for each env1178 });11791180 app.configure('development', function(){1181 // executed for 'development' only1182 });11831184### app.redirect(name, val)11851186For use with _res.redirect()_ we can map redirects at the application level as shown below:11871188 app.redirect('google', 'http://google.com');11891190Now in a route we may call:11911192 res.redirect('google');11931194We may also map dynamic redirects:11951196 app.redirect('comments', function(req, res){1197 return '/post/' + req.params.id + '/comments';1198 });11991200So now we may do the following, and the redirect will dynamically adjust to1201the context of the request. If we called this route with _GET /post/12_ our1202redirect _Location_ would be _/post/12/comments_.12031204 app.get('/post/:id', function(req, res){1205 res.redirect('comments');1206 });12071208When mounted, _res.redirect()_ will respect the mount-point. For example if a blog app is mounted at _/blog_, the following will redirect to _/blog/posts_:12091210 res.redirect('/posts');12111212### app.error(function)12131214Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1215Note that we may set several error handlers by making several calls to this method, however the handler1216should call _next(err)_ if it does not wish to deal with the exception:12171218 app.error(function(err, req, res, next){1219 res.send(err.message, 500);1220 });12211222### app.helpers(obj)12231224Registers static view helpers.12251226 app.helpers({1227 name: function(first, last){ return first + ', ' + last }1228 , firstName: 'tj'1229 , lastName: 'holowaychuk'1230 });12311232Our view could now utilize the _firstName_ and _lastName_ variables,1233as well as the _name()_ function exposed.12341235 <%= name(firstName, lastName) %>12361237Express also provides a few locals by default:12381239 - `settings` the app's settings object

docsTj Holowaychukbefore adoption885fb1f

line 1240why, one step back
1240 - `layout(path)` specify the layout from within a view

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1241–1265why, one step back
1241
1242This method is aliased as _app.locals()_.12431244### app.dynamicHelpers(obj)12451246Registers dynamic view helpers. Dynamic view helpers1247are simply functions which accept _req_, _res_, and are1248evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1249becomes the local variable it is associated with.12501251 app.dynamicHelpers({1252 session: function(req, res){1253 return req.session;1254 }1255 });12561257All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12581259 <%= session.name %>12601261### app.lookup12621263 The _app.lookup_ http methods returns an array of callback functions1264 associated with the given _path_.1265

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1266why, one step back
1266 Suppose we define the following routes:

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1267–1269why, one step back
1267
1268 app.get('/user/:id', function(){});1269 app.put('/user/:id', function(){});

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1270why, one step back
1270 app.get('/user/:id/:op?', function(){});

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1271–1278why, one step back
1271
1272 We can utilize this lookup functionality to check which routes1273 have been defined, which can be extremely useful for higher level1274 frameworks built on Express.12751276 app.lookup.get('/user/:id');1277 // => [Function]1278

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1279why, one step back
1279 app.lookup.get('/user/:id/:op?');

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1280–1296why, one step back
1280 // => [Function]
12811282 app.lookup.put('/user/:id');1283 // => [Function]12841285 app.lookup.all('/user/:id');1286 // => [Function, Function]12871288 app.lookup.all('/hey');1289 // => []12901291 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1292 without a callback, as a shortcut, for example the following are1293 equivalent:1294 1295 app.lookup.get('/user');1296 app.get('/user');

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

line 1297why, one step back
1297

more docsTj Holowaychukbefore adoption6230ec5

lines 1298–1313why, one step back
1298 Each function returned has the following properties:
1299 1300 var fn = app.get('/user/:id/:op?')[0];13011302 fn.regexp1303 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i13041305 fn.keys1306 // => ['id', 'op']13071308 fn.path1309 // => '/user/:id/:op?'13101311 fn.method1312 // => 'GET'1313

docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed

lines 1314–1341why, one step back
1314### app.match
13151316 The _app.match_ http methods return an array of callback functions1317 which match the given _url_, which may include a query string etc. This1318 is useful when you want reflect on which routes have the opportunity to1319 respond.13201321 Suppose we define the following routes:13221323 app.get('/user/:id', function(){});1324 app.put('/user/:id', function(){});1325 app.get('/user/:id/:op?', function(){});13261327 Our match against __GET__ will return two functions, since the _:op_1328 in our second route is optional.13291330 app.match.get('/user/1');1331 // => [Function, Function]13321333 This second call returns only the callback for _/user/:id/:op?_.13341335 app.match.get('/user/23/edit');1336 // => [Function]13371338 We can also use _all()_ to disregard the http method:13391340 app.match.all('/user/20');1341 // => [Function, Function, Function]

more docsTj Holowaychukbefore adoption6230ec5

lines 1342–1354why, one step back
1342
1343 Each function matched has the following properties:1344 1345 var fn = app.match.get('/user/23/edit')[0];13461347 fn.keys1348 // => ['id', 'op']13491350 fn.params1351 // => { id: '23', op: 'edit' }13521353 fn.method1354 // => 'GET'

docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa

lines 1355–1424why, one step back
1355
1356### app.mounted(fn)13571358Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13591360 var app = express.createServer(),1361 blog = express.createServer();1362 1363 blog.mounted(function(parent){1364 // parent is app1365 // "this" is blog1366 });1367 1368 app.use(blog);13691370### app.register(ext, exports)13711372Register the given template engine _exports_1373as _ext_. For example we may wish to map ".html"1374files to jade:13751376 app.register('.html', require('jade'));13771378This is also useful for libraries that may not1379match extensions correctly. For example my haml.js1380library is installed from npm as "hamljs" so instead1381of layout.hamljs, we can register the engine as ".haml":13821383 app.register('.haml', require('haml-js'));13841385For engines that do not comply with the Express1386specification, we can also wrap their api this way. Below1387we map _.md_ to render markdown files, rendering the html once1388since it will not change on subsequent calls, and support local substitution1389in the form of "{name}".13901391 app.register('.md', {1392 compile: function(str, options){1393 var html = md.toHTML(str);1394 return function(locals){1395 return html.replace(/\{([^}]+)\}/g, function(_, name){1396 return locals[name];1397 });1398 };1399 }1400 });14011402### app.listen([port[, host]])14031404Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1405connections will be accepted via _INADDR_ANY_.14061407 app.listen();1408 app.listen(3000);1409 app.listen(3000, 'n.n.n.n');14101411The _port_ argument may also be a string representing the path to a unix domain socket:14121413 app.listen('/tmp/express.sock');14141415Then try it out:14161417 $ telnet /tmp/express.sock1418 GET / HTTP/1.114191420 HTTP/1.1 200 OK1421 Content-Type: text/plain1422 Content-Length: 111423 1424 Hello World