Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,342 lines · 45.3 KiB · Markdown

Last changed by

Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd

History of this file

Take it

The walk stopped after 200 commits: lines older than 4c95031 point at it.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1–5why, one step back
1
2### Installation34 $ npm install express5

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 6why, one step back
6### Creating A Server

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 7why, one step back
7

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 8why, one step back
8 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()_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 9–10why, one step back
9
10 var app = require('express').createServer();

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 11–16why, one step back
11
12 app.get('/', function(req, res){13 res.send('hello world');14 });15 16 app.listen(3000);

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 17why, one step back
17

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 18–24why, one step back
18### Creating An HTTPS Server
1920 To initialize a _express.HTTPSServer_ we do the same as above, however we21 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).22 23 var app = require('express').createServer({ key: ... });24

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 25–32why, one step back
25### Configuration
2627Express supports arbitrary environments, such as _production_ and _development_. Developers28can use the _configure()_ method to setup needs required by the current environment. When29_configure()_ is called without an environment name it will be run in _every_ environment 30prior to the environment specific callback.3132In the example below we only _dumpExceptions_, and respond with exception stack traces

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 33why, one step back
33in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 34why, one step back
34Note the use of _app.router_, which can (optionally) be used to mount the application routes,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 35why, one step back
35otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 36–38why, one step back
36
37 app.configure(function(){38 app.use(express.methodOverride());

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 39why, one step back
39 app.use(express.bodyParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 40–43why, one step back
40 app.use(app.router);
41 });42 43 app.configure('development', function(){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 44why, one step back
44 app.use(express.static(__dirname + '/public'));

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 45–47why, one step back
45 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
46 });47

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 48–49why, one step back
48 app.configure('production', function(){
49 var oneYear = 31557600000;

Docs for staticProvider() changesTj Holowaychukbefore adoption3cacf05

line 50why, one step back
50 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 51–52why, one step back
51 app.use(express.errorHandler());
52 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 53–55why, one step back
53
54For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:55

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 56–69why, one step back
56 app.configure(function(){
57 app.set('views', __dirname + '/views');58 app.set('views');59 // => "/absolute/path/to/views"60 61 app.enable('some feature');62 // same as app.set('some feature', true);63 64 app.disable('some feature');65 // same as app.set('some feature', false);66 67 app.enabled('some feature')68 // => false69 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 70–84why, one step back
70
71To alter the environment we can set the _NODE_ENV_ environment variable, for example:7273 $ NODE_ENV=production node app.js7475This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7677### Settings7879Express supports the following settings out of the box:8081 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.82 * _views_ Root views directory defaulting to **CWD/views**83 * _view engine_ Default view engine name for views rendered without extensions84 * _view options_ An object specifying global view options

docs for "view cache" settingTj Holowaychukbefore adoption805b9ac

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

Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 87–156why, one step back
87
88### Routing8990Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.91For example we may want to render a user's account for the path _/user/12_, this92can be done by defining the route below. The values associated to the named placeholders 93are available as `req.params`.9495 app.get('/user/:id', function(req, res){96 res.send('user ' + req.params.id);97 });9899A route is simple a string which is compiled to a _RegExp_ internally. For example100when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:101102 \/user\/([^\/]+)\/?103104Regular expression literals may also be passed for complex uses. Since capture105groups 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]_.106107 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){108 res.send(req.params);109 });110111Curl requests against the previously defined route:112113 $ curl http://dev:3000/user114 [null,null]115 $ curl http://dev:3000/users116 [null,null]117 $ curl http://dev:3000/users/1118 ["1",null]119 $ curl http://dev:3000/users/1..15120 ["1","15"]121122Below are some route examples, and the associated paths that they123may consume:124125 "/user/:id"126 /user/12127128 "/users/:id?"129 /users/5130 /users131132 "/files/*"133 /files/jquery.js134 /files/javascripts/jquery.js135136 "/file/*.*"137 /files/jquery.js138 /files/javascripts/jquery.js139 140 "/user/:id/:operation?"141 /user/1142 /user/1/edit143 144 "/products.:format"145 /products.json146 /products.xml147148 "/products.:format?"149 /products.json150 /products.xml151 /products152 153 "/user/:id.:format?"154 /user/12155 /user/12.json156

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 157why, one step back
157For 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_:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 158–161why, one step back
158
159 var express = require('express')160 , app = express.createServer();161

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 162why, one step back
162 app.use(express.bodyParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 163–169why, one step back
163
164 app.post('/', function(req, res){165 res.send(req.body);166 });167168 app.listen(3000);169

markdown escapingTj Holowaychukbefore adoptionf0df843

line 170why, one step back
170Typically 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(\\\\d+)'_ which will _not_ match unless the placeholder value contains only digits.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 171–175why, one step back
171
172### Passing Route Control173174We may pass control to the next _matching_ route, by calling the _third_ argument,175the _next()_ function. When a match cannot be made, control is passed back to Connect,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 176why, one step back
176and 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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 177–190why, one step back
177
178 app.get('/users/:id?', function(req, res, next){179 var id = req.params.id;180 if (id) {181 // do something182 } else {183 next();184 }185 });186 187 app.get('/users', function(req, res){188 // do something else189 });190

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 191why, one step back
191The _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_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 192–232why, one step back
192
193 var express = require('express')194 , app = express.createServer();195196 var users = [{ name: 'tj' }];197198 app.all('/user/:id/:op?', function(req, res, next){199 req.user = users[req.params.id];200 if (req.user) {201 next();202 } else {203 next(new Error('cannot find user ' + req.params.id));204 }205 });206207 app.get('/user/:id', function(req, res){208 res.send('viewing ' + req.user.name);209 });210211 app.get('/user/:id/edit', function(req, res){212 res.send('editing ' + req.user.name);213 });214215 app.put('/user/:id', function(req, res){216 res.send('updating ' + req.user.name);217 });218219 app.get('*', function(req, res){220 res.send('what???', 404);221 });222223 app.listen(3000); 224225### Middleware226227Middleware via [Connect](http://github.com/senchalabs/connect) can be228passed to _express.createServer()_ as you would with a regular Connect server. For example:229230 var express = require('express');231232 var app = express.createServer(

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 233–234why, one step back
233 express.logger()
234 , express.bodyParser()

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 235–236why, one step back
235 );
236

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 237why, one step back
237Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 238–244why, one step back
238
239 app.use(express.logger({ format: ':method :uri' }));240241Typically with connect middleware you would _require('connect')_ like so:242243 var connect = require('connect');244 app.use(connect.logger());

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 245why, one step back
245 app.use(connect.bodyParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 246–249why, one step back
246
247This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:248249 app.use(express.logger());

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 250why, one step back
250 app.use(express.bodyParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 251–258why, one step back
251
252### Route Middleware253254Routes 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.255256Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 257258 app.get('/user/:id', function(req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 259–262why, one step back
259 loadUser(req.params.id, function(err, user){
260 if (err) return next(err);261 res.send('Viewing user ' + user.name);262 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 263–267why, one step back
263 });
264265To 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. 266267 function loadUser(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 268–275why, one step back
268 // You would fetch your user from the db
269 var user = users[req.params.id];270 if (user) {271 req.user = user;272 next();273 } else {274 next(new Error('Failed to load user ' + req.params.id));275 }

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 276–278why, one step back
276 }
277 278 app.get('/user/:id', loadUser, function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 279why, one step back
279 res.send('Viewing user ' + req.user.name);

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 280–284why, one step back
280 });
281282Multiple 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.283284 function andRestrictToSelf(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 285–287why, one step back
285 req.authenticatedUser.id == req.user.id
286 ? next()287 : next(new Error('Unauthorized'));

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 288–290why, one step back
288 }
289 290 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 291why, one step back
291 res.send('Editing user ' + req.user.name);

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 292–296why, one step back
292 });
293294Keeping 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.295296 function andRestrictTo(role) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 297–301why, one step back
297 return function(req, res, next) {
298 req.authenticatedUser.role == role299 ? next()300 : next(new Error('Unauthorized'));301 }

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 302–304why, one step back
302 }
303 304 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 305why, one step back
305 res.send('Deleted user ' + req.user.name);

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 306–334why, one step back
306 });
307308Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.309310 var a = [middleware1, middleware2]311 , b = [middleware3, middleware4]312 , all = [a, b];313 314 app.get('/foo', a, function(){});315 app.get('/bar', a, function(){});316 317 app.get('/', a, middleware3, middleware4, function(){});318 app.get('/', a, b, function(){});319 app.get('/', all, function(){});320321For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.322323### HTTP Methods324325We 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.326327 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.328 329 <form method="post" action="/">330 <input type="text" name="user[name]" />331 <input type="text" name="user[email]" />332 <input type="submit" value="Submit" />333 </form>334

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 335why, one step back
335By 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:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 336why, one step back
336

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 337why, one step back
337 app.use(express.bodyParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 338–341why, one step back
338
339Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.340341 app.post('/', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 342–343why, one step back
342 console.log(req.body.user);
343 res.redirect('back');

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 344–345why, one step back
344 });
345

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 346why, one step back
346When 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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 347why, one step back
347

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 348why, one step back
348 app.use(express.bodyParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 349–370why, one step back
349 app.use(express.methodOverride());
350351The 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:352353 <form method="post" action="/">354 <input type="hidden" name="_method" value="put" />355 <input type="text" name="user[name]" />356 <input type="text" name="user[email]" />357 <input type="submit" value="Submit" /> 358 </form>359360 app.put('/', function(){361 console.log(req.body.user);362 res.redirect('back');363 });364365### Error Handling366367Express provides the _app.error()_ method which receives exceptions thrown within a route,368or passed to _next(err)_. Below is an example which serves different pages based on our369ad-hoc _NotFound_ exception:370

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 371–376why, one step back
371 function NotFound(msg){
372 this.name = 'NotFound';373 Error.call(this, msg);374 Error.captureStackTrace(this, arguments.callee);375 }376

doc typoTj Holowaychukbefore adoptionfae1ba9

line 377why, one step back
377 NotFound.prototype.__proto__ = Error.prototype;

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 378–385why, one step back
378
379 app.get('/404', function(req, res){380 throw new NotFound;381 });382 383 app.get('/500', function(req, res){384 throw new Error('keyboard cat!');385 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 386–404why, one step back
386
387We can call _app.error()_ several times as shown below.388Here we check for an instanceof _NotFound_ and show the389404 page, or we pass on to the next error handler.390391Note that these handlers can be defined anywhere, as they392will be placed below the route handlers on _listen()_. This 393allows for definition within _configure()_ blocks so we can394handle exceptions in different ways based on the environment.395396 app.error(function(err, req, res, next){397 if (err instanceof NotFound) {398 res.render('404.jade');399 } else {400 next(err);401 }402 });403404Here we assume all errors as 500 for the simplicity of

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 405why, one step back
405this 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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 406why, one step back
406

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 407–411why, one step back
407 app.error(function(err, req, res){
408 res.render('500.jade', {409 error: err410 });411 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 412–426why, one step back
412
413Our apps could also utilize the Connect _errorHandler_ middleware414to report on exceptions. For example if we wish to output exceptions 415in "development" mode to _stderr_ we can use:416417 app.use(express.errorHandler({ dumpExceptions: true }));418419Also during development we may want fancy html pages to show exceptions420that are passed or thrown, so we can set _showStack_ to true:421422 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));423424The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_425is present, which is useful for developing apps that rely heavily on client-side JavaScript.426

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 427why, one step back
427### Route Param Pre-conditions

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 428why, one step back
428

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 429why, one step back
429Route 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:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 430–437why, one step back
430
431 app.get('/user/:userId', function(req, res, next){432 User.get(req.params.userId, function(err, user){433 if (err) return next(err);434 res.send('user ' + user.name);435 });436 }); 437

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 438why, one step back
438With 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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 439–464why, one step back
439
440 app.param('userId', function(req, res, next, id){441 User.get(id, function(err, user){442 if (err) return next(err);443 if (!user) return next(new Error('failed to find user'));444 req.user = user;445 next();446 });447 });448449Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:450451 app.get('/user/:userId', function(req, res){452 res.send('user ' + req.user.name);453 });454455For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to _next(err)_.456457 app.param('number', function(n){ return parseInt(n, 10); });458459We may also apply the same callback to several placeholders, for example a route GET _/commits/:from-:to_ are both numbers, so we may define them as an array:460461 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });462463### View Rendering464

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 465why, one step back
465View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 466why, one step back
466of the module that will be required. For example the view _layout.ejs_ will

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 467–468why, one step back
467tell 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 behaviour
468_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 469why, one step back
469

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 470–472why, one step back
470Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,
471and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 472the _body_ local variable in _layout.jade_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 473–474why, one step back
473
474 app.get('/', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 475why, one step back
475 res.render('index.jade', { title: 'My Site' });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 476–478why, one step back
476 });
477478The new _view engine_ setting allows us to specify our default template engine,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 479why, one step back
479so for example when using jade we could set:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 480–498why, one step back
480
481 app.set('view engine', 'jade');482483Allowing us to render with:484485 res.render('index');486487vs:488489 res.render('index.jade');490491When _view engine_ is set, extensions are entirely optional, however we can still492mix and match template engines:493494 res.render('another-page.ejs');495496Express 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:497498 app.set('view options', {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 499why, one step back
499 layout: false

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 500–501why, one step back
500 });
501

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 502why, one step back
502Which can then be overridden within the _res.render()_ call if need be:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 503–526why, one step back
503
504 res.render('myview.ejs', { layout: true });505506When 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:507508 res.render('page', { layout: 'mylayout' });509510Otherwise we must specify the extension:511512 res.render('page', { layout: 'mylayout.jade' });513514These paths may also be absolute:515516 res.render('page', { layout: __dirname + '/../../mylayout.jade' });517518A good example of this is specifying custom _ejs_ opening and closing tags:519520 app.set('view options', {521 open: '{{',522 close: '}}'523 });524525### View Partials526

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 527why, one step back
527The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating

docs for partial changesTj Holowaychukbefore adoption20b8fac

line 528why, one step back
528in a view to display comments, we could use partial collection:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 529–531why, one step back
529
530 partial('comment', { collection: comments });531

docs for partial changesTj Holowaychukbefore adoption20b8fac

line 532why, one step back
532If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 533–535why, one step back
533
534 partial('comment', comments);535

docs for partial changesTj Holowaychukbefore adoption20b8fac

line 536why, one step back
536When using the partial collection support a few "magic" locals are provided

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 537–538why, one step back
537for free:
538

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 539–542why, one step back
539 * _firstInCollection_ true if this is the first object
540 * _indexInCollection_ index of the object in the collection541 * _lastInCollection_ true if this is the last object542 * _collectionLength_ length of the collection

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 543why, one step back
543

note on localsTj Holowaychukbefore adoption022c5e1

lines 544–545why, one step back
544Local 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.
545

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 546–547why, one step back
546For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).
547

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 548–554why, one step back
548__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.
549550### View Lookup551552View 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_.553554The 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_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 555why, one step back
555

more docsTj Holowaychukbefore adoption0b6a941

lines 556–557why, one step back
556When 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')_.
557

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 558–561why, one step back
558### Template Engines
559560Below are a few template engines commonly used with Express:561

Add haml back in docsTj Holowaychukbefore adoptione85752c

line 562why, one step back
562 * [Haml](http://github.com/visionmedia/haml.js) haml implementation

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 563–569why, one step back
563 * [Jade](http://jade-lang.com) haml.js successor
564 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript565 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating566 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node567568### Session Support569

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 570why, one step back
570Sessions 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_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 571why, one step back
571

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 572–573why, one step back
572 app.use(express.cookieParser());
573 app.use(express.session({ secret: "keyboard cat" }));

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 574–577why, one step back
574
575By 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:576577 var RedisStore = require('connect-redis');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 578–579why, one step back
578 app.use(express.cookieParser());
579 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 580–583why, one step back
580
581Now 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:582583 var RedisStore = require('connect-redis');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 584–586why, one step back
584 app.use(express.bodyParser());
585 app.use(express.cookieParser());586 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 587–589why, one step back
587
588 app.post('/add-to-cart', function(req, res){589 // Perhaps we posted several items with a form

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 590why, one step back
590 // (use the bodyParser() middleware for this)

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 591–605why, one step back
591 var items = req.body.items;
592 req.session.items = items;593 res.redirect('back');594 });595596 app.get('/add-to-cart', function(req, res){597 // When redirected back to GET /add-to-cart598 // we could check req.session.items && req.session.items.length599 // to print out a message600 if (req.session.items && req.session.items.length) {601 req.flash('info', 'You have %s items in your cart', req.session.items.length);602 }603 res.render('shopping-cart');604 });605

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 606why, one step back
606The _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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 607why, one step back
607

docsTj Holowaychukbefore adoption5581ca2

line 608why, one step back
608### Migration Guide

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 609why, one step back
609

docsTj Holowaychukbefore adoption4609984

line 610why, one step back
610 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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 611–619why, one step back
611
612### req.header(key[, defaultValue])613614Get the case-insensitive request header _key_, with optional _defaultValue_:615616 req.header('Host');617 req.header('host');618 req.header('Accept', '*/*');619

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 620–629why, one step back
620The _Referrer_ and _Referer_ header fields are special-cased, either will work:
621622 // sent Referrer: http://google.com623624 req.header('Referer');625 // => "http://google.com"626627 req.header('Referrer');628 // => "http://google.com"629

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 630–706why, one step back
630### req.accepts(type)
631632Check if the _Accept_ header is present, and includes the given _type_.633634When the _Accept_ header is not present _true_ is returned. Otherwise635the given _type_ is matched by an exact match, and then subtypes. You636may pass the subtype such as "html" which is then converted internally637to "text/html" using the mime lookup table.638639 // Accept: text/html640 req.accepts('html');641 // => true642643 // Accept: text/*; application/json644 req.accepts('html');645 req.accepts('text/html');646 req.accepts('text/plain');647 req.accepts('application/json');648 // => true649650 req.accepts('image/png');651 req.accepts('png');652 // => false653654### req.is(type)655656Check if the incoming request contains the _Content-Type_657header field, and it contains the give mime _type_.658 659 // With Content-Type: text/html; charset=utf-8660 req.is('html');661 req.is('text/html');662 // => true663 664 // When Content-Type is application/json665 req.is('json');666 req.is('application/json');667 // => true668 669 req.is('html');670 // => false671 672Ad-hoc callbacks can also be registered with Express, to perform673assertions again the request, for example if we need an expressive674way to check if our incoming request is an image, we can register _"an image"_675callback:676 677 app.is('an image', function(req){678 return 0 == req.headers['content-type'].indexOf('image');679 });680 681Now within our route callbacks, we can use to to assert content types682such as _"image/jpeg"_, _"image/png"_, etc.683 684 app.post('/image/upload', function(req, res, next){685 if (req.is('an image')) {686 // do something687 } else {688 next();689 }690 });691692Keep in mind this method is _not_ limited to checking _Content-Type_, you693can perform any request assertion you wish.694695Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:696697 req.is('image/*');698699We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.700701 req.is('*/json');702703### req.param(name[, default])704705Return the value of param _name_ when present or _default_.706

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 707why, one step back
707 - Checks route params (_req.params_), ex: /user/:id

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 708–712why, one step back
708 - Checks query string params (_req.query_), ex: ?id=12
709 - Checks urlencoded body params (_req.body_), ex: id=12710711To utilize urlencoded request bodies, _req.body_712should be an object. This can be done by using

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 713why, one step back
713the _express.bodyParser middleware.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 714–751why, one step back
714
715### req.flash(type[, msg])716717Queue flash _msg_ of the given _type_.718719 req.flash('info', 'email sent');720 req.flash('error', 'email delivery failed');721 req.flash('info', 'email re-sent');722 // => 2723724 req.flash('info');725 // => ['email sent', 'email re-sent']726727 req.flash('info');728 // => []729730 req.flash();731 // => { error: ['email delivery failed'], info: [] }732733Flash notification message may also utilize formatters, by default only the %s string formatter is available:734735 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);736737### req.isXMLHttpRequest738739Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header740to see if it was issued by an _XMLHttpRequest_:741742 req.xhr743 req.isXMLHttpRequest744745### res.header(key[, val])746747Get or set the response header _key_.748749 res.header('Content-Length');750 // => undefined751

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 752why, one step back
752 res.header('Content-Length', 123);

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 753why, one step back
753 // => 123

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 754why, one step back
754

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 755–757why, one step back
755 res.header('Content-Length');
756 // => 123757

docs for charsetTj Holowaychukbefore adoptiond12452f

lines 758–775why, one step back
758### res.charset
759760Sets 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:761762 res.charset = 'ISO-8859-1';763 res.render('users');764765or before responding with `res.send()`:766767 res.charset = 'ISO-8859-1';768 res.send(str);769770or with node's `res.end()`:771772 res.charset = 'ISO-8859-1';773 res.header('Content-Type', 'text/plain');774 res.end(str);775

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 776–781why, one step back
776### res.contentType(type)
777778Sets the _Content-Type_ response header to the given _type_.779780 var filename = 'path/to/image.png';781 res.contentType(filename);

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 782why, one step back
782 // Content-Type is now "image/png"

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 783why, one step back
783

docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a

lines 784–787why, one step back
784A literal _Content-Type_ works as well:
785786 res.contentType('application/json');787

Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73

lines 788–791why, one step back
788Or simply the extension without leading `.`:
789790 res.contentType('json');791

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 792–797why, one step back
792### res.attachment([filename])
793794Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.795796 res.attachment('path/to/my/image.png');797

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 798why, one step back
798### res.sendfile(path[, options[, callback]])

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 799–803why, one step back
799
800Used by `res.download()` to transfer an arbitrary file. 801802 res.sendfile('path/to/my.file');803

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 804–805why, one step back
804This method accepts an optional callback which is called when
805an 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.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 806why, one step back
806

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 807why, one step back
807 res.sendfile(path, function(err){

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 808why, one step back
808 if (err) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 809why, one step back
809 next(err);

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 810–814why, one step back
810 } else {
811 console.log('transferred %s', path);812 }813 });814

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 815why, one step back
815Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 816why, one step back
816

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 817–820why, one step back
817 res.sendfile(path, { bufferSize: 1024 }, function(err){
818 // handle819 });820

docsTj Holowaychukbefore adoption236a412

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 822why, one step back
822

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 823–832why, one step back
823Transfer the given _file_ as an attachment with optional alternative _filename_.
824825 res.download('path/to/image.png');826 res.download('path/to/image.png', 'foo.png');827828This is equivalent to:829830 res.attachment(file);831 res.sendfile(file);832

docsTj Holowaychukbefore adoption236a412

line 833why, one step back
833An 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.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 834–836why, one step back
834
835 res.download(path, 'expenses.doc', function(err){836 // handle

docsTj Holowaychukbefore adoption236a412

lines 837–844why, one step back
837 });
838839An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.840841 res.download(path, function(err){842 // error or finished843 }, function(err){844 // connection related error

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 845–846why, one step back
845 });
846

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 847–848why, one step back
847### res.send(body|status[, headers|status[, status]])
848

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 849–850why, one step back
849The _res.send()_ method is a high level response utility allowing you to pass
850objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 851–863why, one step back
851
852 res.send(); // 204853 res.send(new Buffer('wahoo'));854 res.send({ some: 'json' });855 res.send('<p>some html</p>');856 res.send('Sorry, cant find that', 404);857 res.send('text', { 'Content-Type': 'text/plain' }, 201);858 res.send(404);859860By default the _Content-Type_ response header is set, however if explicitly861assigned through `res.send()` or previously with `res.header()` or `res.contentType()`862it will not be set again.863

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 864why, one step back
864Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 865–881why, one step back
865
866### res.redirect(url[, status])867868Redirect to the given _url_ with a default response _status_ of 302.869870 res.redirect('/', 301);871 res.redirect('/account');872 res.redirect('http://google.com');873 res.redirect('home');874 res.redirect('back');875876Express supports "redirect mapping", which by default provides _home_, and _back_.877The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes878the "home" setting and defaults to "/".879880### res.cookie(name, val[, options])881

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 882why, one step back
882Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 883–886why, one step back
883
884 // "Remember me" for 15 minutes 885 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });886

docs for res.cookie()Tj Holowaychukbefore adoption00e1dbf

lines 887–890why, one step back
887The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:
888889 res.cookie('rememberme', 'yes', { maxAge: 900000 });890

doc typoTj Holowaychukbefore adoption62df63d

line 891why, one step back
891To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 892why, one step back
892

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 893why, one step back
893 app.use(express.cookieParser());

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 894–895why, one step back
894
895 app.get('/', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 896why, one step back
896 // use req.cookies.rememberme

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 897–898why, one step back
897 });
898

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 900–910why, one step back
900
901Clear cookie _name_ by setting "expires" far in the past.902903 res.clearCookie('rememberme');904905### res.render(view[, options[, fn]])906907Render _view_ with the given _options_ and optional callback _fn_.908When a callback function is given a response will _not_ be made909automatically, however otherwise a response of _200_ and _text/html_ is given.910

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 911why, one step back
911The _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:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 912why, one step back
912

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 913–914why, one step back
913 var user = { name: 'tj' };
914 res.render('index', { layout: false, user: user });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 915–950why, one step back
915
916### res.partial(view[, options])917918Render _view_ partial with the given _options_. This method is always available919to the view as a local variable.920921- _object_ the object named by _as_ or derived from the view name922- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.923 * as: 'something' will add the _something_ local variable924 * as: this will use the collection value as the template context925 * as: global will merge the collection value's properties with _locals_926927- _collection_ Array of objects, the name is derived from the view name itself. 928 For example _video.html_ will have a object _video_ available to it.929930The following are equivalent, and the name of collection value when passed931to the partial will be _movie_ as derived from the name.932933 partial('theatre/movie.jade', { collection: movies });934 partial('theatre/movie.jade', movies);935 partial('movie.jade', { collection: movies });936 partial('movie.jade', movies);937 partial('movie', movies);938 // In view: movie.director939940To change the local from _movie_ to _video_ we can use the "as" option:941942 partial('movie', { collection: movies, as: 'video' });943 // In view: video.director944945Also we can make our movie the value of _this_ within our view so that instead946of _movie.director_ we could use _this.director_.947948 partial('movie', { collection: movies, as: this });949 // In view: this.director950

docs for partial changesTj Holowaychukbefore adoption20b8fac

line 951why, one step back
951Another alternative is to "expand" the properties of the collection item into

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 952–972why, one step back
952pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:
953954 partial('movie', { collection: movies, as: global });955 // In view: director956957This same logic applies to a single partial object usage:958959 partial('movie', { object: movie, as: this });960 // In view: this.director961962 partial('movie', { object: movie, as: global });963 // In view: director964965 partial('movie', { object: movie, as: 'video' });966 // In view: video.director967968 partial('movie', { object: movie });969 // In view: movie.director970971When 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:972

docs for partial changesTj Holowaychukbefore adoption20b8fac

lines 973–974why, one step back
973 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')
974 partial('movie', movie)

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 975why, one step back
975 // => In view: movie.director

docs for partial changesTj Holowaychukbefore adoption20b8fac

lines 976–986why, one step back
976
977The 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:978979 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 980 partial('movie', movie)981982For 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:983984 partial('movie', { locals: { movie: movie }})985 partial('movie', { movie: movie })986 partial('movie', { object: movie })

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 987why, one step back
987

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 988–1002why, one step back
988This 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:
989990 app.get('/users', function(req, res){991 if (req.xhr) {992 // respond with the each user in the collection993 // passed to the "user" view994 res.partial('user', users);995 } else {996 // respond with layout, and users page997 // which internally does partial('user', users)998 // along with other UI999 res.render('users', { users: users });1000 }1001 });1002

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1003–1019why, one step back
1003### res.local(name[, val])
10041005Get 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()`.10061007 app.all('/movie/:id', function(req, res, next){1008 Movie.get(req.params.id, function(err, movie){1009 // Assigns res.locals.movie = movie1010 res.local('movie', movie);1011 });1012 });1013 1014 app.get('/movie/:id', function(req, res){1015 // movie is already a local, however we1016 // can pass more if we wish1017 res.render('movie', { displayReviews: true });1018 });1019

doc typoTj Holowaychukbefore adoptionc3e6326

line 1020why, one step back
1020### res.locals(obj)

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 1021–1028why, one step back
1021
1022 Assign several locals with the given _obj_. The following are equivalent:1023 1024 res.local('foo', bar);1025 res.local('bar', baz);10261027 res.locals({ foo: bar, bar, baz });1028

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1029–1053why, one step back
1029### app.set(name[, val])
10301031Apply an application level setting _name_ to _val_, or1032get the value of _name_ when _val_ is not present:10331034 app.set('views', __dirname + '/views');1035 app.set('views');1036 // => ...path...10371038Alternatively you may simply access the settings via _app.settings_:10391040 app.settings.views1041 // => ...path...10421043### app.enable(name)10441045Enable the given setting _name_:10461047 app.enable('some arbitrary setting');1048 app.set('some arbitrary setting');1049 // => true10501051 app.enabled('some arbitrary setting');1052 // => true1053

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1054–1064why, one step back
1054### app.enabled(name)
10551056Check if setting _name_ is enabled:10571058 app.enabled('view cache');1059 // => false10601061 app.enable('view cache');1062 app.enabled('view cache');1063 // => true1064

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1065–1075why, one step back
1065### app.disable(name)
10661067Disable the given setting _name_:10681069 app.disable('some setting');1070 app.set('some setting');1071 // => false1072 1073 app.disabled('some setting');1074 // => false1075

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1076–1088why, one step back
1076### app.disabled(name)
10771078Check if setting _name_ is disabled:10791080 app.enable('view cache');10811082 app.disabled('view cache');1083 // => false10841085 app.disable('view cache');1086 app.disabled('view cache');1087 // => true1088

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1089–1102why, one step back
1089### app.configure(env|function[, function])
10901091Define a callback function for the given _env_ (or all environments) with callback _function_:10921093 app.configure(function(){1094 // executed for each env1095 });10961097 app.configure('development', function(){1098 // executed for 'development' only1099 });11001101### app.redirect(name, val)1102

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1103why, one step back
1103For use with _res.redirect()_ we can map redirects at the application level as shown below:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1104–1113why, one step back
1104
1105 app.redirect('google', 'http://google.com');11061107Now in a route we may call:11081109 res.redirect('google');11101111We may also map dynamic redirects:11121113 app.redirect('comments', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1114why, one step back
1114 return '/post/' + req.params.id + '/comments';

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1115–1121why, one step back
1115 });
11161117So now we may do the following, and the redirect will dynamically adjust to1118the context of the request. If we called this route with _GET /post/12_ our1119redirect _Location_ would be _/post/12/comments_.11201121 app.get('/post/:id', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1122why, one step back
1122 res.redirect('comments');

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1123–1124why, one step back
1123 });
1124

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1125–1128why, one step back
1125When 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_:
11261127 res.redirect('/posts');1128

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1129–1135why, one step back
1129### app.error(function)
11301131Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1132Note that we may set several error handlers by making several calls to this method, however the handler1133should call _next(err)_ if it does not wish to deal with the exception:11341135 app.error(function(err, req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1136–1137why, one step back
1136 res.send(err.message, 500);
1137 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1138–1142why, one step back
1138
1139### app.helpers(obj)11401141Registers static view helpers.1142

Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29

lines 1143–1147why, one step back
1143 app.helpers({
1144 name: function(first, last){ return first + ', ' + last }1145 , firstName: 'tj'1146 , lastName: 'holowaychuk'1147 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1148–1152why, one step back
1148
1149Our view could now utilize the _firstName_ and _lastName_ variables,1150as well as the _name()_ function exposed.11511152 <%= name(firstName, lastName) %>

Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29

lines 1153–1156why, one step back
1153
1154Express also provides a few locals by default:11551156 - `settings` the app's settings object

docs for "filename" localTj Holowaychukbefore adoptionbf06d90

line 1157why, one step back
1157 - `filename` the view's filename

docsTj Holowaychukbefore adoption885fb1f

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

Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29

lines 1159–1160why, one step back
1159
1160This method is aliased as _app.locals()_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1161–1169why, one step back
1161
1162### app.dynamicHelpers(obj)11631164Registers dynamic view helpers. Dynamic view helpers1165are simply functions which accept _req_, _res_, and are1166evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1167becomes the local variable it is associated with.11681169 app.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1170–1172why, one step back
1170 session: function(req, res){
1171 return req.session;1172 }

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1173–1178why, one step back
1173 });
11741175All views would now have _session_ available so that session data can be accessed via _session.name_ etc:11761177 <%= session.name %>1178

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

lines 1179–1183why, one step back
1179### app.lookup
11801181 The _app.lookup_ http methods returns an array of callback functions1182 associated with the given _path_.1183

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

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

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

lines 1185–1187why, one step back
1185
1186 app.get('/user/:id', function(){});1187 app.put('/user/:id', function(){});

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

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

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

lines 1189–1196why, one step back
1189
1190 We can utilize this lookup functionality to check which routes1191 have been defined, which can be extremely useful for higher level1192 frameworks built on Express.11931194 app.lookup.get('/user/:id');1195 // => [Function]1196

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

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

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

lines 1198–1214why, one step back
1198 // => [Function]
11991200 app.lookup.put('/user/:id');1201 // => [Function]12021203 app.lookup.all('/user/:id');1204 // => [Function, Function]12051206 app.lookup.all('/hey');1207 // => []12081209 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1210 without a callback, as a shortcut, for example the following are1211 equivalent:1212 1213 app.lookup.get('/user');1214 app.get('/user');

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

line 1215why, one step back
1215

more docsTj Holowaychukbefore adoption6230ec5

lines 1216–1231why, one step back
1216 Each function returned has the following properties:
1217 1218 var fn = app.get('/user/:id/:op?')[0];12191220 fn.regexp1221 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12221223 fn.keys1224 // => ['id', 'op']12251226 fn.path1227 // => '/user/:id/:op?'12281229 fn.method1230 // => 'GET'1231

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

lines 1232–1259why, one step back
1232### app.match
12331234 The _app.match_ http methods return an array of callback functions1235 which match the given _url_, which may include a query string etc. This1236 is useful when you want reflect on which routes have the opportunity to1237 respond.12381239 Suppose we define the following routes:12401241 app.get('/user/:id', function(){});1242 app.put('/user/:id', function(){});1243 app.get('/user/:id/:op?', function(){});12441245 Our match against __GET__ will return two functions, since the _:op_1246 in our second route is optional.12471248 app.match.get('/user/1');1249 // => [Function, Function]12501251 This second call returns only the callback for _/user/:id/:op?_.12521253 app.match.get('/user/23/edit');1254 // => [Function]12551256 We can also use _all()_ to disregard the http method:12571258 app.match.all('/user/20');1259 // => [Function, Function, Function]

more docsTj Holowaychukbefore adoption6230ec5

lines 1260–1272why, one step back
1260
1261 Each function matched has the following properties:1262 1263 var fn = app.match.get('/user/23/edit')[0];12641265 fn.keys1266 // => ['id', 'op']12671268 fn.params1269 // => { id: '23', op: 'edit' }12701271 fn.method1272 // => 'GET'

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

line 1273why, one step back
1273

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1274–1281why, one step back
1274### app.mounted(fn)
12751276Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.12771278 var app = express.createServer(),1279 blog = express.createServer();1280 1281 blog.mounted(function(parent){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1282–1283why, one step back
1282 // parent is app
1283 // "this" is blog

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1284–1303why, one step back
1284 });
1285 1286 app.use(blog);12871288### app.register(ext, exports)12891290Register the given template engine _exports_1291as _ext_. For example we may wish to map ".html"1292files to jade:12931294 app.register('.html', require('jade'));12951296This is also useful for libraries that may not1297match extensions correctly. For example my haml.js1298library is installed from npm as "hamljs" so instead1299of layout.hamljs, we can register the engine as ".haml":13001301 app.register('.haml', require('haml-js'));13021303For engines that do not comply with the Express

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1304–1307why, one step back
1304specification, we can also wrap their api this way. Below
1305we map _.md_ to render markdown files, rendering the html once1306since it will not change on subsequent calls, and support local substitution1307in the form of "{name}".

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 1308why, one step back
1308

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1309–1318why, one step back
1309 app.register('.md', {
1310 compile: function(str, options){1311 var html = md.toHTML(str);1312 return function(locals){1313 return html.replace(/\{([^}]+)\}/g, function(_, name){1314 return locals[name];1315 });1316 };1317 }1318 });

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1319–1342why, one step back
1319
1320### app.listen([port[, host]])13211322Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1323connections will be accepted via _INADDR_ANY_.13241325 app.listen();1326 app.listen(3000);1327 app.listen(3000, 'n.n.n.n');13281329The _port_ argument may also be a string representing the path to a unix domain socket:13301331 app.listen('/tmp/express.sock');13321333Then try it out:13341335 $ telnet /tmp/express.sock1336 GET / HTTP/1.113371338 HTTP/1.1 200 OK1339 Content-Type: text/plain1340 Content-Length: 111341 1342 Hello World