Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,344 lines · 45.6 KiB · Markdown

Last changed by

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

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–322why, 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.322

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 325–336why, one step back
325### HTTP Methods
326327We 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.328329 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.330 331 <form method="post" action="/">332 <input type="text" name="user[name]" />333 <input type="text" name="user[email]" />334 <input type="submit" value="Submit" />335 </form>336

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 337why, one step back
337By 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 338why, one step back
338

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 346–347why, one step back
346 });
347

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 348why, one step back
348When 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 349why, one step back
349

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

doc typoTj Holowaychukbefore adoptionfae1ba9

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 388–406why, one step back
388
389We can call _app.error()_ several times as shown below.390Here we check for an instanceof _NotFound_ and show the391404 page, or we pass on to the next error handler.392393Note that these handlers can be defined anywhere, as they394will be placed below the route handlers on _listen()_. This 395allows for definition within _configure()_ blocks so we can396handle exceptions in different ways based on the environment.397398 app.error(function(err, req, res, next){399 if (err instanceof NotFound) {400 res.render('404.jade');401 } else {402 next(err);403 }404 });405406Here we assume all errors as 500 for the simplicity of

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 407why, one step back
407this 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 408why, one step back
408

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 430why, one step back
430

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 431why, one step back
431Route 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 432–439why, one step back
432
433 app.get('/user/:userId', function(req, res, next){434 User.get(req.params.userId, function(err, user){435 if (err) return next(err);436 res.send('user ' + user.name);437 });438 }); 439

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 440why, one step back
440With 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 441–466why, one step back
441
442 app.param('userId', function(req, res, next, id){443 User.get(id, function(err, user){444 if (err) return next(err);445 if (!user) return next(new Error('failed to find user'));446 req.user = user;447 next();448 });449 });450451Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:452453 app.get('/user/:userId', function(req, res){454 res.send('user ' + req.user.name);455 });456457For 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)_.458459 app.param('number', function(n){ return parseInt(n, 10); });460461We 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:462463 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });464465### View Rendering466

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 469–470why, one step back
469tell 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
470_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 471why, one step back
471

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 501why, one step back
501 layout: false

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 502–503why, one step back
502 });
503

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 529why, one step back
529The 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 530why, one step back
530in a view to display comments, we could use partial collection:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

line 534why, one step back
534If 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 535–537why, one step back
535
536 partial('comment', comments);537

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 539–540why, one step back
539for free:
540

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 541–544why, one step back
541 * _firstInCollection_ true if this is the first object
542 * _indexInCollection_ index of the object in the collection543 * _lastInCollection_ true if this is the last object544 * _collectionLength_ length of the collection

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 545why, one step back
545

note on localsTj Holowaychukbefore adoption022c5e1

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 550–556why, one step back
550__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.
551552### View Lookup553554View 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_.555556The 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 557why, one step back
557

more docsTj Holowaychukbefore adoption0b6a941

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 560–563why, one step back
560### Template Engines
561562Below are a few template engines commonly used with Express:563

Add haml back in docsTj Holowaychukbefore adoptione85752c

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 565–571why, one step back
565 * [Jade](http://jade-lang.com) haml.js successor
566 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript567 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating568 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node569570### Session Support571

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 572why, one step back
572Sessions 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 573why, one step back
573

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 593–607why, one step back
593 var items = req.body.items;
594 req.session.items = items;595 res.redirect('back');596 });597598 app.get('/add-to-cart', function(req, res){599 // When redirected back to GET /add-to-cart600 // we could check req.session.items && req.session.items.length601 // to print out a message602 if (req.session.items && req.session.items.length) {603 req.flash('info', 'You have %s items in your cart', req.session.items.length);604 }605 res.render('shopping-cart');606 });607

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

docsTj Holowaychukbefore adoption5581ca2

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 611why, one step back
611

docsTj Holowaychukbefore adoption4609984

line 612why, one step back
612 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 613–621why, one step back
613
614### req.header(key[, defaultValue])615616Get the case-insensitive request header _key_, with optional _defaultValue_:617618 req.header('Host');619 req.header('host');620 req.header('Accept', '*/*');621

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 622–631why, one step back
622The _Referrer_ and _Referer_ header fields are special-cased, either will work:
623624 // sent Referrer: http://google.com625626 req.header('Referer');627 // => "http://google.com"628629 req.header('Referrer');630 // => "http://google.com"631

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 632–708why, one step back
632### req.accepts(type)
633634Check if the _Accept_ header is present, and includes the given _type_.635636When the _Accept_ header is not present _true_ is returned. Otherwise637the given _type_ is matched by an exact match, and then subtypes. You638may pass the subtype such as "html" which is then converted internally639to "text/html" using the mime lookup table.640641 // Accept: text/html642 req.accepts('html');643 // => true644645 // Accept: text/*; application/json646 req.accepts('html');647 req.accepts('text/html');648 req.accepts('text/plain');649 req.accepts('application/json');650 // => true651652 req.accepts('image/png');653 req.accepts('png');654 // => false655656### req.is(type)657658Check if the incoming request contains the _Content-Type_659header field, and it contains the give mime _type_.660 661 // With Content-Type: text/html; charset=utf-8662 req.is('html');663 req.is('text/html');664 // => true665 666 // When Content-Type is application/json667 req.is('json');668 req.is('application/json');669 // => true670 671 req.is('html');672 // => false673 674Ad-hoc callbacks can also be registered with Express, to perform675assertions again the request, for example if we need an expressive676way to check if our incoming request is an image, we can register _"an image"_677callback:678 679 app.is('an image', function(req){680 return 0 == req.headers['content-type'].indexOf('image');681 });682 683Now within our route callbacks, we can use to to assert content types684such as _"image/jpeg"_, _"image/png"_, etc.685 686 app.post('/image/upload', function(req, res, next){687 if (req.is('an image')) {688 // do something689 } else {690 next();691 }692 });693694Keep in mind this method is _not_ limited to checking _Content-Type_, you695can perform any request assertion you wish.696697Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:698699 req.is('image/*');700701We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.702703 req.is('*/json');704705### req.param(name[, default])706707Return the value of param _name_ when present or _default_.708

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 710–714why, one step back
710 - Checks query string params (_req.query_), ex: ?id=12
711 - Checks urlencoded body params (_req.body_), ex: id=12712713To utilize urlencoded request bodies, _req.body_714should be an object. This can be done by using

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 716–753why, one step back
716
717### req.flash(type[, msg])718719Queue flash _msg_ of the given _type_.720721 req.flash('info', 'email sent');722 req.flash('error', 'email delivery failed');723 req.flash('info', 'email re-sent');724 // => 2725726 req.flash('info');727 // => ['email sent', 'email re-sent']728729 req.flash('info');730 // => []731732 req.flash();733 // => { error: ['email delivery failed'], info: [] }734735Flash notification message may also utilize formatters, by default only the %s string formatter is available:736737 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);738739### req.isXMLHttpRequest740741Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header742to see if it was issued by an _XMLHttpRequest_:743744 req.xhr745 req.isXMLHttpRequest746747### res.header(key[, val])748749Get or set the response header _key_.750751 res.header('Content-Length');752 // => undefined753

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 756why, one step back
756

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 757–759why, one step back
757 res.header('Content-Length');
758 // => 123759

docs for charsetTj Holowaychukbefore adoptiond12452f

lines 760–777why, one step back
760### res.charset
761762Sets 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:763764 res.charset = 'ISO-8859-1';765 res.render('users');766767or before responding with `res.send()`:768769 res.charset = 'ISO-8859-1';770 res.send(str);771772or with node's `res.end()`:773774 res.charset = 'ISO-8859-1';775 res.header('Content-Type', 'text/plain');776 res.end(str);777

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 785why, one step back
785

docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a

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

Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73

lines 790–793why, one step back
790Or simply the extension without leading `.`:
791792 res.contentType('json');793

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 801–805why, one step back
801
802Used by `res.download()` to transfer an arbitrary file. 803804 res.sendfile('path/to/my.file');805

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 818why, one step back
818

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 819–822why, one step back
819 res.sendfile(path, { bufferSize: 1024 }, function(err){
820 // handle821 });822

docsTj Holowaychukbefore adoption236a412

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 824why, one step back
824

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 825–834why, one step back
825Transfer the given _file_ as an attachment with optional alternative _filename_.
826827 res.download('path/to/image.png');828 res.download('path/to/image.png', 'foo.png');829830This is equivalent to:831832 res.attachment(file);833 res.sendfile(file);834

docsTj Holowaychukbefore adoption236a412

line 835why, one step back
835An 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 836–838why, one step back
836
837 res.download(path, 'expenses.doc', function(err){838 // handle

docsTj Holowaychukbefore adoption236a412

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 847–848why, one step back
847 });
848

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 851–852why, one step back
851The _res.send()_ method is a high level response utility allowing you to pass
852objects 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 853–865why, one step back
853
854 res.send(); // 204855 res.send(new Buffer('wahoo'));856 res.send({ some: 'json' });857 res.send('<p>some html</p>');858 res.send('Sorry, cant find that', 404);859 res.send('text', { 'Content-Type': 'text/plain' }, 201);860 res.send(404);861862By default the _Content-Type_ response header is set, however if explicitly863assigned through `res.send()` or previously with `res.header()` or `res.contentType()`864it will not be set again.865

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 866why, one step back
866Note 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 867–883why, one step back
867
868### res.redirect(url[, status])869870Redirect to the given _url_ with a default response _status_ of 302.871872 res.redirect('/', 301);873 res.redirect('/account');874 res.redirect('http://google.com');875 res.redirect('home');876 res.redirect('back');877878Express supports "redirect mapping", which by default provides _home_, and _back_.879The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes880the "home" setting and defaults to "/".881882### res.cookie(name, val[, options])883

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for res.cookie()Tj Holowaychukbefore adoption00e1dbf

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

doc typoTj Holowaychukbefore adoption62df63d

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 894why, one step back
894

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 899–900why, one step back
899 });
900

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 917–952why, one step back
917
918### res.partial(view[, options])919920Render _view_ partial with the given _options_. This method is always available921to the view as a local variable.922923- _object_ the object named by _as_ or derived from the view name924- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.925 * as: 'something' will add the _something_ local variable926 * as: this will use the collection value as the template context927 * as: global will merge the collection value's properties with _locals_928929- _collection_ Array of objects, the name is derived from the view name itself. 930 For example _video.html_ will have a object _video_ available to it.931932The following are equivalent, and the name of collection value when passed933to the partial will be _movie_ as derived from the name.934935 partial('theatre/movie.jade', { collection: movies });936 partial('theatre/movie.jade', movies);937 partial('movie.jade', { collection: movies });938 partial('movie.jade', movies);939 partial('movie', movies);940 // In view: movie.director941942To change the local from _movie_ to _video_ we can use the "as" option:943944 partial('movie', { collection: movies, as: 'video' });945 // In view: video.director946947Also we can make our movie the value of _this_ within our view so that instead948of _movie.director_ we could use _this.director_.949950 partial('movie', { collection: movies, as: this });951 // In view: this.director952

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 954–974why, one step back
954pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:
955956 partial('movie', { collection: movies, as: global });957 // In view: director958959This same logic applies to a single partial object usage:960961 partial('movie', { object: movie, as: this });962 // In view: this.director963964 partial('movie', { object: movie, as: global });965 // In view: director966967 partial('movie', { object: movie, as: 'video' });968 // In view: video.director969970 partial('movie', { object: movie });971 // In view: movie.director972973When 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:974

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

lines 978–988why, one step back
978
979The 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:980981 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 982 partial('movie', movie)983984For 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:985986 partial('movie', { locals: { movie: movie }})987 partial('movie', { movie: movie })988 partial('movie', { object: movie })

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 989why, one step back
989

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 990–1004why, one step back
990This 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:
991992 app.get('/users', function(req, res){993 if (req.xhr) {994 // respond with the each user in the collection995 // passed to the "user" view996 res.partial('user', users);997 } else {998 // respond with layout, and users page999 // which internally does partial('user', users)1000 // along with other UI1001 res.render('users', { users: users });1002 }1003 });1004

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1005–1021why, one step back
1005### res.local(name[, val])
10061007Get 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()`.10081009 app.all('/movie/:id', function(req, res, next){1010 Movie.get(req.params.id, function(err, movie){1011 // Assigns res.locals.movie = movie1012 res.local('movie', movie);1013 });1014 });1015 1016 app.get('/movie/:id', function(req, res){1017 // movie is already a local, however we1018 // can pass more if we wish1019 res.render('movie', { displayReviews: true });1020 });1021

doc typoTj Holowaychukbefore adoptionc3e6326

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

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1031–1055why, one step back
1031### app.set(name[, val])
10321033Apply an application level setting _name_ to _val_, or1034get the value of _name_ when _val_ is not present:10351036 app.set('views', __dirname + '/views');1037 app.set('views');1038 // => ...path...10391040Alternatively you may simply access the settings via _app.settings_:10411042 app.settings.views1043 // => ...path...10441045### app.enable(name)10461047Enable the given setting _name_:10481049 app.enable('some arbitrary setting');1050 app.set('some arbitrary setting');1051 // => true10521053 app.enabled('some arbitrary setting');1054 // => true1055

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1056–1066why, one step back
1056### app.enabled(name)
10571058Check if setting _name_ is enabled:10591060 app.enabled('view cache');1061 // => false10621063 app.enable('view cache');1064 app.enabled('view cache');1065 // => true1066

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1067–1077why, one step back
1067### app.disable(name)
10681069Disable the given setting _name_:10701071 app.disable('some setting');1072 app.set('some setting');1073 // => false1074 1075 app.disabled('some setting');1076 // => false1077

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1078–1090why, one step back
1078### app.disabled(name)
10791080Check if setting _name_ is disabled:10811082 app.enable('view cache');10831084 app.disabled('view cache');1085 // => false10861087 app.disable('view cache');1088 app.disabled('view cache');1089 // => true1090

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1091–1104why, one step back
1091### app.configure(env|function[, function])
10921093Define a callback function for the given _env_ (or all environments) with callback _function_:10941095 app.configure(function(){1096 // executed for each env1097 });10981099 app.configure('development', function(){1100 // executed for 'development' only1101 });11021103### app.redirect(name, val)1104

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1125–1126why, one step back
1125 });
1126

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1140–1144why, one step back
1140
1141### app.helpers(obj)11421143Registers static view helpers.1144

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

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

docs for "filename" localTj Holowaychukbefore adoptionbf06d90

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

docsTj Holowaychukbefore adoption885fb1f

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

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1163–1171why, one step back
1163
1164### app.dynamicHelpers(obj)11651166Registers dynamic view helpers. Dynamic view helpers1167are simply functions which accept _req_, _res_, and are1168evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1169becomes the local variable it is associated with.11701171 app.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

lines 1181–1185why, one step back
1181### app.lookup
11821183 The _app.lookup_ http methods returns an array of callback functions1184 associated with the given _path_.1185

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

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

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

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

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

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

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

lines 1191–1198why, one step back
1191
1192 We can utilize this lookup functionality to check which routes1193 have been defined, which can be extremely useful for higher level1194 frameworks built on Express.11951196 app.lookup.get('/user/:id');1197 // => [Function]1198

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

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

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

lines 1200–1216why, one step back
1200 // => [Function]
12011202 app.lookup.put('/user/:id');1203 // => [Function]12041205 app.lookup.all('/user/:id');1206 // => [Function, Function]12071208 app.lookup.all('/hey');1209 // => []12101211 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1212 without a callback, as a shortcut, for example the following are1213 equivalent:1214 1215 app.lookup.get('/user');1216 app.get('/user');

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

line 1217why, one step back
1217

more docsTj Holowaychukbefore adoption6230ec5

lines 1218–1233why, one step back
1218 Each function returned has the following properties:
1219 1220 var fn = app.get('/user/:id/:op?')[0];12211222 fn.regexp1223 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12241225 fn.keys1226 // => ['id', 'op']12271228 fn.path1229 // => '/user/:id/:op?'12301231 fn.method1232 // => 'GET'1233

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

lines 1234–1261why, one step back
1234### app.match
12351236 The _app.match_ http methods return an array of callback functions1237 which match the given _url_, which may include a query string etc. This1238 is useful when you want reflect on which routes have the opportunity to1239 respond.12401241 Suppose we define the following routes:12421243 app.get('/user/:id', function(){});1244 app.put('/user/:id', function(){});1245 app.get('/user/:id/:op?', function(){});12461247 Our match against __GET__ will return two functions, since the _:op_1248 in our second route is optional.12491250 app.match.get('/user/1');1251 // => [Function, Function]12521253 This second call returns only the callback for _/user/:id/:op?_.12541255 app.match.get('/user/23/edit');1256 // => [Function]12571258 We can also use _all()_ to disregard the http method:12591260 app.match.all('/user/20');1261 // => [Function, Function, Function]

more docsTj Holowaychukbefore adoption6230ec5

lines 1262–1274why, one step back
1262
1263 Each function matched has the following properties:1264 1265 var fn = app.match.get('/user/23/edit')[0];12661267 fn.keys1268 // => ['id', 'op']12691270 fn.params1271 // => { id: '23', op: 'edit' }12721273 fn.method1274 // => 'GET'

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

line 1275why, one step back
1275

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1284–1285why, one step back
1284 // parent is app
1285 // "this" is blog

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1286–1305why, one step back
1286 });
1287 1288 app.use(blog);12891290### app.register(ext, exports)12911292Register the given template engine _exports_1293as _ext_. For example we may wish to map ".html"1294files to jade:12951296 app.register('.html', require('jade'));12971298This is also useful for libraries that may not1299match extensions correctly. For example my haml.js1300library is installed from npm as "hamljs" so instead1301of layout.hamljs, we can register the engine as ".haml":13021303 app.register('.haml', require('haml-js'));13041305For engines that do not comply with the Express

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 1310why, one step back
1310

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1321–1344why, one step back
1321
1322### app.listen([port[, host]])13231324Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1325connections will be accepted via _INADDR_ANY_.13261327 app.listen();1328 app.listen(3000);1329 app.listen(3000, 'n.n.n.n');13301331The _port_ argument may also be a string representing the path to a unix domain socket:13321333 app.listen('/tmp/express.sock');13341335Then try it out:13361337 $ telnet /tmp/express.sock1338 GET / HTTP/1.113391340 HTTP/1.1 200 OK1341 Content-Type: text/plain1342 Content-Length: 111343 1344 Hello World