Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,167 lines · 39.3 KiB · Markdown

Last changed by

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

History of this file

Take it

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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()_.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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);

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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_.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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());

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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'));

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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–52why, one step back
48 app.configure('production', function(){
49 var oneYear = 31557600000;50 app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));51 app.use(express.errorHandler());52 });

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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 });

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 70–102why, 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 options8586### Routing8788Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.89For example we may want to render a user's account for the path _/user/12_, this90can be done by defining the route below. The values associated to the named placeholders 91are available as `req.params`.9293 app.get('/user/:id', function(req, res){94 res.send('user ' + req.params.id);95 });9697A route is simple a string which is compiled to a _RegExp_ internally. For example98when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:99100 \/user\/([^\/]+)\/?101102Regular expression literals may also be passed for complex uses. Since capture

DocsTj Holowaychukbefore adoptionbba049b

line 103why, one step back
103groups 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]_.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 104–149why, one step back
104
105 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){106 res.send(req.params);107 });108109Curl requests against the previously defined route:110111 $ curl http://dev:3000/user112 [null,null]113 $ curl http://dev:3000/users114 [null,null]115 $ curl http://dev:3000/users/1116 ["1",null]117 $ curl http://dev:3000/users/1..15118 ["1","15"]119120Below are some route examples, and the associated paths that they121may consume:122123 "/user/:id"124 /user/12125126 "/users/:id?"127 /users/5128 /users129130 "/files/*"131 /files/jquery.js132 /files/javascripts/jquery.js133134 "/file/*.*"135 /files/jquery.js136 /files/javascripts/jquery.js137 138 "/user/:id/:operation?"139 /user/1140 /user/1/edit141 142 "/products.:format"143 /products.json144 /products.xml145146 "/products.:format?"147 /products.json148 /products.xml149 /products

DocsTj Holowaychukbefore adoptionbba049b

lines 150–153why, one step back
150
151 "/user/:id.:format?"152 /user/12153 /user/12.json

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 154why, one step back
154

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

DocsTj Holowaychukbefore adoptionbba049b

line 167why, one step back
167

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 190–230why, one step back
190
191 var express = require('express')192 , app = express.createServer();193194 var users = [{ name: 'tj' }];195196 app.all('/user/:id/:op?', function(req, res, next){197 req.user = users[req.params.id];198 if (req.user) {199 next();200 } else {201 next(new Error('cannot find user ' + req.params.id));202 }203 });204205 app.get('/user/:id', function(req, res){206 res.send('viewing ' + req.user.name);207 });208209 app.get('/user/:id/edit', function(req, res){210 res.send('editing ' + req.user.name);211 });212213 app.put('/user/:id', function(req, res){214 res.send('updating ' + req.user.name);215 });216217 app.get('*', function(req, res){218 res.send('what???', 404);219 });220221 app.listen(3000); 222223### Middleware224225Middleware via [Connect](http://github.com/senchalabs/connect) can be226passed to _express.createServer()_ as you would with a regular Connect server. For example:227228 var express = require('express');229230 var app = express.createServer(

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 231–232why, one step back
231 express.logger()
232 , express.bodyParser()

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 233–234why, one step back
233 );
234

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 295–299why, one step back
295 return function(req, res, next) {
296 req.authenticatedUser.role == role297 ? next()298 : next(new Error('Unauthorized'));299 }

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 334why, one step back
334

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 342–343why, one step back
342 });
343

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 345why, one step back
345

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 369–383why, one step back
369 function NotFound(msg){
370 this.name = 'NotFound';371 Error.call(this, msg);372 Error.captureStackTrace(this, arguments.callee);373 }374 375 NotFound.protoype.__proto__ = Error.prototype;376 377 app.get('/404', function(req, res){378 throw new NotFound;379 });380 381 app.get('/500', function(req, res){382 throw new Error('keyboard cat!');383 });

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 404why, one step back
404

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

line 426why, one step back
426

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

lines 437–460why, one step back
437
438 app.param('userId', function(req, res, next, id){439 User.get(id, function(err, user){440 if (err) return next(err);441 if (!user) return next(new Error('failed to find user'));442 req.user = user;443 next();444 });445 });446447Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:448449 app.get('/user/:userId', function(req, res){450 res.send('user ' + req.user.name);451 });452453For 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)_.454455 app.param('number', function(n){ return parseInt(n, 10); });456457We 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:458459 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });460

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 461–462why, one step back
461### View Rendering
462

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 467why, one step back
467

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 497why, one step back
497 layout: false

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 498–499why, one step back
498 });
499

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 526–529why, one step back
526in a view to display comments, we would use a partial with collection support:
527528 partial('comment', { collection: comments });529

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 531–536why, one step back
531
532 partial('comment', comments);533534When using the partial collection support a few "magic" variables are provided535for free:536

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 537–540why, one step back
537 * _firstInCollection_ true if this is the first object
538 * _indexInCollection_ index of the object in the collection539 * _lastInCollection_ true if this is the last object540 * _collectionLength_ length of the collection

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

more partial docsTj Holowaychukbefore adoptionf32279d

line 543why, one step back
543

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 544why, one step back
544NOTE: 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.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 545–556why, one step back
545
546### Template Engines547548Below are a few template engines commonly used with Express:549550 * [Jade](http://jade-lang.com) haml.js successor551 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript552 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating553 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node554555### Session Support556

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 558why, one step back
558

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 561–564why, one step back
561
562By 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:563564 var RedisStore = require('connect-redis');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 567–570why, one step back
567
568Now 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:569570 var RedisStore = require('connect-redis');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 578–592why, one step back
578 var items = req.body.items;
579 req.session.items = items;580 res.redirect('back');581 });582583 app.get('/add-to-cart', function(req, res){584 // When redirected back to GET /add-to-cart585 // we could check req.session.items && req.session.items.length586 // to print out a message587 if (req.session.items && req.session.items.length) {588 req.flash('info', 'You have %s items in your cart', req.session.items.length);589 }590 res.render('shopping-cart');591 });592

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 594–596why, one step back
594
595### Migration Guide596

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 597why, one step back
597 Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 598–606why, one step back
598
599### req.header(key[, defaultValue])600601Get the case-insensitive request header _key_, with optional _defaultValue_:602603 req.header('Host');604 req.header('host');605 req.header('Accept', '*/*');606

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 607–616why, one step back
607The _Referrer_ and _Referer_ header fields are special-cased, either will work:
608609 // sent Referrer: http://google.com610611 req.header('Referer');612 // => "http://google.com"613614 req.header('Referrer');615 // => "http://google.com"616

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 617–689why, one step back
617### req.accepts(type)
618619Check if the _Accept_ header is present, and includes the given _type_.620621When the _Accept_ header is not present _true_ is returned. Otherwise622the given _type_ is matched by an exact match, and then subtypes. You623may pass the subtype such as "html" which is then converted internally624to "text/html" using the mime lookup table.625626 // Accept: text/html627 req.accepts('html');628 // => true629630 // Accept: text/*; application/json631 req.accepts('html');632 req.accepts('text/html');633 req.accepts('text/plain');634 req.accepts('application/json');635 // => true636637 req.accepts('image/png');638 req.accepts('png');639 // => false640641### req.is(type)642643Check if the incoming request contains the _Content-Type_644header field, and it contains the give mime _type_.645 646 // With Content-Type: text/html; charset=utf-8647 req.is('html');648 req.is('text/html');649 // => true650 651 // When Content-Type is application/json652 req.is('json');653 req.is('application/json');654 // => true655 656 req.is('html');657 // => false658 659Ad-hoc callbacks can also be registered with Express, to perform660assertions again the request, for example if we need an expressive661way to check if our incoming request is an image, we can register _"an image"_662callback:663 664 app.is('an image', function(req){665 return 0 == req.headers['content-type'].indexOf('image');666 });667 668Now within our route callbacks, we can use to to assert content types669such as _"image/jpeg"_, _"image/png"_, etc.670 671 app.post('/image/upload', function(req, res, next){672 if (req.is('an image')) {673 // do something674 } else {675 next();676 }677 });678679Keep in mind this method is _not_ limited to checking _Content-Type_, you680can perform any request assertion you wish.681682Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:683684 req.is('image/*');685686We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.687688 req.is('*/json');689

Added default param support to req.param(name, default)Tj Holowaychukbefore adoption0af9126

line 690why, one step back
690### req.param(name[, default])

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 691why, one step back
691

Added default param support to req.param(name, default)Tj Holowaychukbefore adoption0af9126

line 692why, one step back
692Return the value of param _name_ when present or _default_.

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 693why, one step back
693

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 695–699why, one step back
695 - Checks query string params (_req.query_), ex: ?id=12
696 - Checks urlencoded body params (_req.body_), ex: id=12697698To utilize urlencoded request bodies, _req.body_699should be an object. This can be done by using

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 701–738why, one step back
701
702### req.flash(type[, msg])703704Queue flash _msg_ of the given _type_.705706 req.flash('info', 'email sent');707 req.flash('error', 'email delivery failed');708 req.flash('info', 'email re-sent');709 // => 2710711 req.flash('info');712 // => ['email sent', 'email re-sent']713714 req.flash('info');715 // => []716717 req.flash();718 // => { error: ['email delivery failed'], info: [] }719720Flash notification message may also utilize formatters, by default only the %s string formatter is available:721722 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);723724### req.isXMLHttpRequest725726Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header727to see if it was issued by an _XMLHttpRequest_:728729 req.xhr730 req.isXMLHttpRequest731732### res.header(key[, val])733734Get or set the response header _key_.735736 res.header('Content-Length');737 // => undefined738

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 741why, one step back
741

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 742–750why, one step back
742 res.header('Content-Length');
743 // => 123744745### res.contentType(type)746747Sets the _Content-Type_ response header to the given _type_.748749 var filename = 'path/to/image.png';750 res.contentType(filename);

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 752–758why, one step back
752
753### res.attachment([filename])754755Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.756757 res.attachment('path/to/my/image.png');758

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 760–764why, one step back
760
761Used by `res.download()` to transfer an arbitrary file. 762763 res.sendfile('path/to/my.file');764

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 767why, one step back
767

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 771–775why, one step back
771 } else {
772 console.log('transferred %s', path);773 }774 });775

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 777why, one step back
777

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 778–783why, one step back
778 res.sendfile(path, { bufferSize: 1024 }, function(err){
779 // handle780 });781782### res.download(file[, filename[, callback]])783

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 784–793why, one step back
784Transfer the given _file_ as an attachment with optional alternative _filename_.
785786 res.download('path/to/image.png');787 res.download('path/to/image.png', 'foo.png');788789This is equivalent to:790791 res.attachment(file);792 res.sendfile(file);793

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 794–799why, one step back
794An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_:
795796 res.download(path, 'expenses.doc', function(err){797 // handle798 });799

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 804–816why, one step back
804
805 res.send(); // 204806 res.send(new Buffer('wahoo'));807 res.send({ some: 'json' });808 res.send('<p>some html</p>');809 res.send('Sorry, cant find that', 404);810 res.send('text', { 'Content-Type': 'text/plain' }, 201);811 res.send(404);812813By default the _Content-Type_ response header is set, however if explicitly814assigned through `res.send()` or previously with `res.header()` or `res.contentType()`815it will not be set again.816

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 818–834why, one step back
818
819### res.redirect(url[, status])820821Redirect to the given _url_ with a default response _status_ of 302.822823 res.redirect('/', 301);824 res.redirect('/account');825 res.redirect('http://google.com');826 res.redirect('home');827 res.redirect('back');828829Express supports "redirect mapping", which by default provides _home_, and _back_.830The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes831the "home" setting and defaults to "/".832833### res.cookie(name, val[, options])834

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 836–841why, one step back
836
837 // "Remember me" for 15 minutes 838 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });839840To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:841

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 846–859why, one step back
846 });
847848### res.clearCookie(name)849850Clear cookie _name_ by setting "expires" far in the past.851852 res.clearCookie('rememberme');853854### res.render(view[, options[, fn]])855856Render _view_ with the given _options_ and optional callback _fn_.857When a callback function is given a response will _not_ be made858automatically, however otherwise a response of _200_ and _text/html_ is given.859

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 861why, one step back
861

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 864–924why, one step back
864
865### res.partial(view[, options])866867Render _view_ partial with the given _options_. This method is always available868to the view as a local variable.869870- _object_ the object named by _as_ or derived from the view name871- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.872 * as: 'something' will add the _something_ local variable873 * as: this will use the collection value as the template context874 * as: global will merge the collection value's properties with _locals_875876- _collection_ Array of objects, the name is derived from the view name itself. 877 For example _video.html_ will have a object _video_ available to it.878879The following are equivalent, and the name of collection value when passed880to the partial will be _movie_ as derived from the name.881882 partial('theatre/movie.jade', { collection: movies });883 partial('theatre/movie.jade', movies);884 partial('movie.jade', { collection: movies });885 partial('movie.jade', movies);886 partial('movie', movies);887 // In view: movie.director888889To change the local from _movie_ to _video_ we can use the "as" option:890891 partial('movie', { collection: movies, as: 'video' });892 // In view: video.director893894Also we can make our movie the value of _this_ within our view so that instead895of _movie.director_ we could use _this.director_.896897 partial('movie', { collection: movies, as: this });898 // In view: this.director899900Another alternative is to "explode" the properties of the collection item into901pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:902903 partial('movie', { collection: movies, as: global });904 // In view: director905906This same logic applies to a single partial object usage:907908 partial('movie', { object: movie, as: this });909 // In view: this.director910911 partial('movie', { object: movie, as: global });912 // In view: director913914 partial('movie', { object: movie, as: 'video' });915 // In view: video.director916917 partial('movie', { object: movie });918 // In view: movie.director919920When 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:921922 partial('movie', movie);923 // => In view: movie.director924

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 925–939why, one step back
925This 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:
926927 app.get('/users', function(req, res){928 if (req.xhr) {929 // respond with the each user in the collection930 // passed to the "user" view931 res.partial('user', users);932 } else {933 // respond with layout, and users page934 // which internally does partial('user', users)935 // along with other UI936 res.render('users', { users: users });937 }938 });939

Added res.local(name[, val]) docsTj Holowaychukbefore adoption5ac0c6d

lines 940–956why, one step back
940### res.local(name[, val])
941942Get 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()`.943944 app.all('/movie/:id', function(req, res, next){945 Movie.get(req.params.id, function(err, movie){946 // Assigns res.locals.movie = movie947 res.local('movie', movie);948 });949 });950 951 app.get('/movie/:id', function(req, res){952 // movie is already a local, however we953 // can pass more if we wish954 res.render('movie', { displayReviews: true });955 });956

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 957–978why, one step back
957### app.set(name[, val])
958959Apply an application level setting _name_ to _val_, or960get the value of _name_ when _val_ is not present:961962 app.set('views', __dirname + '/views');963 app.set('views');964 // => ...path...965966Alternatively you may simply access the settings via _app.settings_:967968 app.settings.views969 // => ...path...970971### app.enable(name)972973Enable the given setting _name_:974975 app.enable('some arbitrary setting');976 app.set('some arbitrary setting');977 // => true978

Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2

lines 979–981why, one step back
979 app.enabled('some arbitrary setting');
980 // => true981

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 982–992why, one step back
982### app.enabled(name)
983984Check if setting _name_ is enabled:985986 app.enabled('view cache');987 // => false988989 app.enable('view cache');990 app.enabled('view cache');991 // => true992

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 993–998why, one step back
993### app.disable(name)
994995Disable the given setting _name_:996997 app.disable('some setting');998 app.set('some setting');

Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2

lines 999–1001why, one step back
999 // => false
1000 1001 app.disabled('some setting');

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1002–1003why, one step back
1002 // => false
1003

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1004–1016why, one step back
1004### app.disabled(name)
10051006Check if setting _name_ is disabled:10071008 app.enable('view cache');10091010 app.disabled('view cache');1011 // => false10121013 app.disable('view cache');1014 app.disabled('view cache');1015 // => true1016

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1017–1030why, one step back
1017### app.configure(env|function[, function])
10181019Define a callback function for the given _env_ (or all environments) with callback _function_:10201021 app.configure(function(){1022 // executed for each env1023 });10241025 app.configure('development', function(){1026 // executed for 'development' only1027 });10281029### app.redirect(name, val)1030

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1032–1041why, one step back
1032
1033 app.redirect('google', 'http://google.com');10341035Now in a route we may call:10361037 res.redirect('google');10381039We may also map dynamic redirects:10401041 app.redirect('comments', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1051–1052why, one step back
1051 });
1052

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1066–1070why, one step back
1066
1067### app.helpers(obj)10681069Registers static view helpers.1070

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1071–1075why, one step back
1071 app.helpers({
1072 name: function(first, last){ return first + ', ' + last }1073 , firstName: 'tj'1074 , lastName: 'holowaychuk'1075 });

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1076–1089why, one step back
1076
1077Our view could now utilize the _firstName_ and _lastName_ variables,1078as well as the _name()_ function exposed.10791080 <%= name(firstName, lastName) %>10811082### app.dynamicHelpers(obj)10831084Registers dynamic view helpers. Dynamic view helpers1085are simply functions which accept _req_, _res_, and are1086evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1087becomes the local variable it is associated with.10881089 app.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1090–1092why, one step back
1090 session: function(req, res){
1091 return req.session;1092 }

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1093–1106why, one step back
1093 });
10941095All views would now have _session_ available so that session data can be accessed via _session.name_ etc:10961097 <%= session.name %>10981099### app.mounted(fn)11001101Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.11021103 var app = express.createServer(),1104 blog = express.createServer();1105 1106 blog.mounted(function(parent){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1107–1108why, one step back
1107 // parent is app
1108 // "this" is blog

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1109–1128why, one step back
1109 });
1110 1111 app.use(blog);11121113### app.register(ext, exports)11141115Register the given template engine _exports_1116as _ext_. For example we may wish to map ".html"1117files to jade:11181119 app.register('.html', require('jade'));11201121This is also useful for libraries that may not1122match extensions correctly. For example my haml.js1123library is installed from npm as "hamljs" so instead1124of layout.hamljs, we can register the engine as ".haml":11251126 app.register('.haml', require('haml-js'));11271128For engines that do not comply with the Express

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

line 1133why, one step back
1133

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1134–1143why, one step back
1134 app.register('.md', {
1135 compile: function(str, options){1136 var html = md.toHTML(str);1137 return function(locals){1138 return html.replace(/\{([^}]+)\}/g, function(_, name){1139 return locals[name];1140 });1141 };1142 }1143 });

fixed route-separation exampleTj Holowaychukbefore adoptionf9d2432

lines 1144–1167why, one step back
1144
1145### app.listen([port[, host]])11461147Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1148connections will be accepted via _INADDR_ANY_.11491150 app.listen();1151 app.listen(3000);1152 app.listen(3000, 'n.n.n.n');11531154The _port_ argument may also be a string representing the path to a unix domain socket:11551156 app.listen('/tmp/express.sock');11571158Then try it out:11591160 $ telnet /tmp/express.sock1161 GET / HTTP/1.111621163 HTTP/1.1 200 OK1164 Content-Type: text/plain1165 Content-Length: 111166 1167 Hello World