Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,341 lines · 45.3 KiB · Markdown

Last changed by

docs for "view cache" settingTj Holowaychukbefore adoption805b9ac

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)

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 86–155why, one step back
86
87### Routing8889Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.90For example we may want to render a user's account for the path _/user/12_, this91can be done by defining the route below. The values associated to the named placeholders 92are available as `req.params`.9394 app.get('/user/:id', function(req, res){95 res.send('user ' + req.params.id);96 });9798A route is simple a string which is compiled to a _RegExp_ internally. For example99when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:100101 \/user\/([^\/]+)\/?102103Regular expression literals may also be passed for complex uses. Since capture104groups 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]_.105106 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){107 res.send(req.params);108 });109110Curl requests against the previously defined route:111112 $ curl http://dev:3000/user113 [null,null]114 $ curl http://dev:3000/users115 [null,null]116 $ curl http://dev:3000/users/1117 ["1",null]118 $ curl http://dev:3000/users/1..15119 ["1","15"]120121Below are some route examples, and the associated paths that they122may consume:123124 "/user/:id"125 /user/12126127 "/users/:id?"128 /users/5129 /users130131 "/files/*"132 /files/jquery.js133 /files/javascripts/jquery.js134135 "/file/*.*"136 /files/jquery.js137 /files/javascripts/jquery.js138 139 "/user/:id/:operation?"140 /user/1141 /user/1/edit142 143 "/products.:format"144 /products.json145 /products.xml146147 "/products.:format?"148 /products.json149 /products.xml150 /products151 152 "/user/:id.:format?"153 /user/12154 /user/12.json155

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 156why, one step back
156For 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 157–160why, one step back
157
158 var express = require('express')159 , app = express.createServer();160

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

markdown escapingTj Holowaychukbefore adoptionf0df843

line 169why, one step back
169Typically 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 170–174why, one step back
170
171### Passing Route Control172173We may pass control to the next _matching_ route, by calling the _third_ argument,174the _next()_ function. When a match cannot be made, control is passed back to Connect,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 175why, one step back
175and 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 176–189why, one step back
176
177 app.get('/users/:id?', function(req, res, next){178 var id = req.params.id;179 if (id) {180 // do something181 } else {182 next();183 }184 });185 186 app.get('/users', function(req, res){187 // do something else188 });189

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 190why, one step back
190The _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 191–231why, one step back
191
192 var express = require('express')193 , app = express.createServer();194195 var users = [{ name: 'tj' }];196197 app.all('/user/:id/:op?', function(req, res, next){198 req.user = users[req.params.id];199 if (req.user) {200 next();201 } else {202 next(new Error('cannot find user ' + req.params.id));203 }204 });205206 app.get('/user/:id', function(req, res){207 res.send('viewing ' + req.user.name);208 });209210 app.get('/user/:id/edit', function(req, res){211 res.send('editing ' + req.user.name);212 });213214 app.put('/user/:id', function(req, res){215 res.send('updating ' + req.user.name);216 });217218 app.get('*', function(req, res){219 res.send('what???', 404);220 });221222 app.listen(3000); 223224### Middleware225226Middleware via [Connect](http://github.com/senchalabs/connect) can be227passed to _express.createServer()_ as you would with a regular Connect server. For example:228229 var express = require('express');230231 var app = express.createServer(

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 262–266why, one step back
262 });
263264To 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. 265266 function loadUser(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 279–283why, one step back
279 });
280281Multiple 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.282283 function andRestrictToSelf(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 291–295why, one step back
291 });
292293Keeping 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.294295 function andRestrictTo(role) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

doc typoTj Holowaychukbefore adoptionfae1ba9

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 427why, one step back
427

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 437why, one step back
437With 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 438–463why, one step back
438
439 app.param('userId', function(req, res, next, id){440 User.get(id, function(err, user){441 if (err) return next(err);442 if (!user) return next(new Error('failed to find user'));443 req.user = user;444 next();445 });446 });447448Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:449450 app.get('/user/:userId', function(req, res){451 res.send('user ' + req.user.name);452 });453454For 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)_.455456 app.param('number', function(n){ return parseInt(n, 10); });457458We 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:459460 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });461462### View Rendering463

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 466–467why, one step back
466tell 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
467_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 468why, one step back
468

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 475–477why, one step back
475 });
476477The new _view engine_ setting allows us to specify our default template engine,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 479–497why, one step back
479
480 app.set('view engine', 'jade');481482Allowing us to render with:483484 res.render('index');485486vs:487488 res.render('index.jade');489490When _view engine_ is set, extensions are entirely optional, however we can still491mix and match template engines:492493 res.render('another-page.ejs');494495Express 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:496497 app.set('view options', {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 498why, one step back
498 layout: false

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 502–525why, one step back
502
503 res.render('myview.ejs', { layout: true });504505When 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:506507 res.render('page', { layout: 'mylayout' });508509Otherwise we must specify the extension:510511 res.render('page', { layout: 'mylayout.jade' });512513These paths may also be absolute:514515 res.render('page', { layout: __dirname + '/../../mylayout.jade' });516517A good example of this is specifying custom _ejs_ opening and closing tags:518519 app.set('view options', {520 open: '{{',521 close: '}}'522 });523524### View Partials525

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 538–541why, one step back
538 * _firstInCollection_ true if this is the first object
539 * _indexInCollection_ index of the object in the collection540 * _lastInCollection_ true if this is the last object541 * _collectionLength_ length of the collection

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 542why, one step back
542

note on localsTj Holowaychukbefore adoption022c5e1

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 547–553why, one step back
547__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.
548549### View Lookup550551View 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_.552553The 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 554why, one step back
554

more docsTj Holowaychukbefore adoption0b6a941

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Add haml back in docsTj Holowaychukbefore adoptione85752c

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 562–568why, one step back
562 * [Jade](http://jade-lang.com) haml.js successor
563 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript564 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating565 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node566567### Session Support568

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

docsTj Holowaychukbefore adoption5581ca2

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 608why, one step back
608

docsTj Holowaychukbefore adoption4609984

line 609why, one step back
609 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 610–618why, one step back
610
611### req.header(key[, defaultValue])612613Get the case-insensitive request header _key_, with optional _defaultValue_:614615 req.header('Host');616 req.header('host');617 req.header('Accept', '*/*');618

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 619–628why, one step back
619The _Referrer_ and _Referer_ header fields are special-cased, either will work:
620621 // sent Referrer: http://google.com622623 req.header('Referer');624 // => "http://google.com"625626 req.header('Referrer');627 // => "http://google.com"628

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 629–705why, one step back
629### req.accepts(type)
630631Check if the _Accept_ header is present, and includes the given _type_.632633When the _Accept_ header is not present _true_ is returned. Otherwise634the given _type_ is matched by an exact match, and then subtypes. You635may pass the subtype such as "html" which is then converted internally636to "text/html" using the mime lookup table.637638 // Accept: text/html639 req.accepts('html');640 // => true641642 // Accept: text/*; application/json643 req.accepts('html');644 req.accepts('text/html');645 req.accepts('text/plain');646 req.accepts('application/json');647 // => true648649 req.accepts('image/png');650 req.accepts('png');651 // => false652653### req.is(type)654655Check if the incoming request contains the _Content-Type_656header field, and it contains the give mime _type_.657 658 // With Content-Type: text/html; charset=utf-8659 req.is('html');660 req.is('text/html');661 // => true662 663 // When Content-Type is application/json664 req.is('json');665 req.is('application/json');666 // => true667 668 req.is('html');669 // => false670 671Ad-hoc callbacks can also be registered with Express, to perform672assertions again the request, for example if we need an expressive673way to check if our incoming request is an image, we can register _"an image"_674callback:675 676 app.is('an image', function(req){677 return 0 == req.headers['content-type'].indexOf('image');678 });679 680Now within our route callbacks, we can use to to assert content types681such as _"image/jpeg"_, _"image/png"_, etc.682 683 app.post('/image/upload', function(req, res, next){684 if (req.is('an image')) {685 // do something686 } else {687 next();688 }689 });690691Keep in mind this method is _not_ limited to checking _Content-Type_, you692can perform any request assertion you wish.693694Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:695696 req.is('image/*');697698We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.699700 req.is('*/json');701702### req.param(name[, default])703704Return the value of param _name_ when present or _default_.705

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 713–750why, one step back
713
714### req.flash(type[, msg])715716Queue flash _msg_ of the given _type_.717718 req.flash('info', 'email sent');719 req.flash('error', 'email delivery failed');720 req.flash('info', 'email re-sent');721 // => 2722723 req.flash('info');724 // => ['email sent', 'email re-sent']725726 req.flash('info');727 // => []728729 req.flash();730 // => { error: ['email delivery failed'], info: [] }731732Flash notification message may also utilize formatters, by default only the %s string formatter is available:733734 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);735736### req.isXMLHttpRequest737738Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header739to see if it was issued by an _XMLHttpRequest_:740741 req.xhr742 req.isXMLHttpRequest743744### res.header(key[, val])745746Get or set the response header _key_.747748 res.header('Content-Length');749 // => undefined750

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 753why, one step back
753

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for charsetTj Holowaychukbefore adoptiond12452f

lines 757–774why, one step back
757### res.charset
758759Sets 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:760761 res.charset = 'ISO-8859-1';762 res.render('users');763764or before responding with `res.send()`:765766 res.charset = 'ISO-8859-1';767 res.send(str);768769or with node's `res.end()`:770771 res.charset = 'ISO-8859-1';772 res.header('Content-Type', 'text/plain');773 res.end(str);774

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 782why, one step back
782

docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a

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

Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 815why, one step back
815

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 816–819why, one step back
816 res.sendfile(path, { bufferSize: 1024 }, function(err){
817 // handle818 });819

docsTj Holowaychukbefore adoption236a412

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 821why, one step back
821

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 822–831why, one step back
822Transfer the given _file_ as an attachment with optional alternative _filename_.
823824 res.download('path/to/image.png');825 res.download('path/to/image.png', 'foo.png');826827This is equivalent to:828829 res.attachment(file);830 res.sendfile(file);831

docsTj Holowaychukbefore adoption236a412

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

docsTj Holowaychukbefore adoption236a412

lines 836–843why, one step back
836 });
837838An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.839840 res.download(path, function(err){841 // error or finished842 }, function(err){843 // connection related error

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 863why, one step back
863Note 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 864–880why, one step back
864
865### res.redirect(url[, status])866867Redirect to the given _url_ with a default response _status_ of 302.868869 res.redirect('/', 301);870 res.redirect('/account');871 res.redirect('http://google.com');872 res.redirect('home');873 res.redirect('back');874875Express supports "redirect mapping", which by default provides _home_, and _back_.876The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes877the "home" setting and defaults to "/".878879### res.cookie(name, val[, options])880

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for res.cookie()Tj Holowaychukbefore adoption00e1dbf

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

doc typoTj Holowaychukbefore adoption62df63d

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 891why, one step back
891

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 914–949why, one step back
914
915### res.partial(view[, options])916917Render _view_ partial with the given _options_. This method is always available918to the view as a local variable.919920- _object_ the object named by _as_ or derived from the view name921- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.922 * as: 'something' will add the _something_ local variable923 * as: this will use the collection value as the template context924 * as: global will merge the collection value's properties with _locals_925926- _collection_ Array of objects, the name is derived from the view name itself. 927 For example _video.html_ will have a object _video_ available to it.928929The following are equivalent, and the name of collection value when passed930to the partial will be _movie_ as derived from the name.931932 partial('theatre/movie.jade', { collection: movies });933 partial('theatre/movie.jade', movies);934 partial('movie.jade', { collection: movies });935 partial('movie.jade', movies);936 partial('movie', movies);937 // In view: movie.director938939To change the local from _movie_ to _video_ we can use the "as" option:940941 partial('movie', { collection: movies, as: 'video' });942 // In view: video.director943944Also we can make our movie the value of _this_ within our view so that instead945of _movie.director_ we could use _this.director_.946947 partial('movie', { collection: movies, as: this });948 // In view: this.director949

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

lines 975–985why, one step back
975
976The 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:977978 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 979 partial('movie', movie)980981For 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:982983 partial('movie', { locals: { movie: movie }})984 partial('movie', { movie: movie })985 partial('movie', { object: movie })

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 986why, one step back
986

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 987–1001why, one step back
987This 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:
988989 app.get('/users', function(req, res){990 if (req.xhr) {991 // respond with the each user in the collection992 // passed to the "user" view993 res.partial('user', users);994 } else {995 // respond with layout, and users page996 // which internally does partial('user', users)997 // along with other UI998 res.render('users', { users: users });999 }1000 });1001

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1002–1018why, one step back
1002### res.local(name[, val])
10031004Get 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()`.10051006 app.all('/movie/:id', function(req, res, next){1007 Movie.get(req.params.id, function(err, movie){1008 // Assigns res.locals.movie = movie1009 res.local('movie', movie);1010 });1011 });1012 1013 app.get('/movie/:id', function(req, res){1014 // movie is already a local, however we1015 // can pass more if we wish1016 res.render('movie', { displayReviews: true });1017 });1018

doc typoTj Holowaychukbefore adoptionc3e6326

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

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1028–1052why, one step back
1028### app.set(name[, val])
10291030Apply an application level setting _name_ to _val_, or1031get the value of _name_ when _val_ is not present:10321033 app.set('views', __dirname + '/views');1034 app.set('views');1035 // => ...path...10361037Alternatively you may simply access the settings via _app.settings_:10381039 app.settings.views1040 // => ...path...10411042### app.enable(name)10431044Enable the given setting _name_:10451046 app.enable('some arbitrary setting');1047 app.set('some arbitrary setting');1048 // => true10491050 app.enabled('some arbitrary setting');1051 // => true1052

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1053–1063why, one step back
1053### app.enabled(name)
10541055Check if setting _name_ is enabled:10561057 app.enabled('view cache');1058 // => false10591060 app.enable('view cache');1061 app.enabled('view cache');1062 // => true1063

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1064–1074why, one step back
1064### app.disable(name)
10651066Disable the given setting _name_:10671068 app.disable('some setting');1069 app.set('some setting');1070 // => false1071 1072 app.disabled('some setting');1073 // => false1074

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1075–1087why, one step back
1075### app.disabled(name)
10761077Check if setting _name_ is disabled:10781079 app.enable('view cache');10801081 app.disabled('view cache');1082 // => false10831084 app.disable('view cache');1085 app.disabled('view cache');1086 // => true1087

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1088–1101why, one step back
1088### app.configure(env|function[, function])
10891090Define a callback function for the given _env_ (or all environments) with callback _function_:10911092 app.configure(function(){1093 // executed for each env1094 });10951096 app.configure('development', function(){1097 // executed for 'development' only1098 });10991100### app.redirect(name, val)1101

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1103–1112why, one step back
1103
1104 app.redirect('google', 'http://google.com');11051106Now in a route we may call:11071108 res.redirect('google');11091110We may also map dynamic redirects:11111112 app.redirect('comments', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1137–1141why, one step back
1137
1138### app.helpers(obj)11391140Registers static view helpers.1141

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

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

docs for "filename" localTj Holowaychukbefore adoptionbf06d90

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

docsTj Holowaychukbefore adoption885fb1f

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

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1160–1168why, one step back
1160
1161### app.dynamicHelpers(obj)11621163Registers dynamic view helpers. Dynamic view helpers1164are simply functions which accept _req_, _res_, and are1165evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1166becomes the local variable it is associated with.11671168 app.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

lines 1178–1182why, one step back
1178### app.lookup
11791180 The _app.lookup_ http methods returns an array of callback functions1181 associated with the given _path_.1182

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

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

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

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

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

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

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

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

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

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

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

lines 1197–1213why, one step back
1197 // => [Function]
11981199 app.lookup.put('/user/:id');1200 // => [Function]12011202 app.lookup.all('/user/:id');1203 // => [Function, Function]12041205 app.lookup.all('/hey');1206 // => []12071208 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1209 without a callback, as a shortcut, for example the following are1210 equivalent:1211 1212 app.lookup.get('/user');1213 app.get('/user');

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

line 1214why, one step back
1214

more docsTj Holowaychukbefore adoption6230ec5

lines 1215–1230why, one step back
1215 Each function returned has the following properties:
1216 1217 var fn = app.get('/user/:id/:op?')[0];12181219 fn.regexp1220 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12211222 fn.keys1223 // => ['id', 'op']12241225 fn.path1226 // => '/user/:id/:op?'12271228 fn.method1229 // => 'GET'1230

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

lines 1231–1258why, one step back
1231### app.match
12321233 The _app.match_ http methods return an array of callback functions1234 which match the given _url_, which may include a query string etc. This1235 is useful when you want reflect on which routes have the opportunity to1236 respond.12371238 Suppose we define the following routes:12391240 app.get('/user/:id', function(){});1241 app.put('/user/:id', function(){});1242 app.get('/user/:id/:op?', function(){});12431244 Our match against __GET__ will return two functions, since the _:op_1245 in our second route is optional.12461247 app.match.get('/user/1');1248 // => [Function, Function]12491250 This second call returns only the callback for _/user/:id/:op?_.12511252 app.match.get('/user/23/edit');1253 // => [Function]12541255 We can also use _all()_ to disregard the http method:12561257 app.match.all('/user/20');1258 // => [Function, Function, Function]

more docsTj Holowaychukbefore adoption6230ec5

lines 1259–1271why, one step back
1259
1260 Each function matched has the following properties:1261 1262 var fn = app.match.get('/user/23/edit')[0];12631264 fn.keys1265 // => ['id', 'op']12661267 fn.params1268 // => { id: '23', op: 'edit' }12691270 fn.method1271 // => 'GET'

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

line 1272why, one step back
1272

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1283–1302why, one step back
1283 });
1284 1285 app.use(blog);12861287### app.register(ext, exports)12881289Register the given template engine _exports_1290as _ext_. For example we may wish to map ".html"1291files to jade:12921293 app.register('.html', require('jade'));12941295This is also useful for libraries that may not1296match extensions correctly. For example my haml.js1297library is installed from npm as "hamljs" so instead1298of layout.hamljs, we can register the engine as ".haml":12991300 app.register('.haml', require('haml-js'));13011302For engines that do not comply with the Express

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 1307why, one step back
1307

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1318–1341why, one step back
1318
1319### app.listen([port[, host]])13201321Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1322connections will be accepted via _INADDR_ANY_.13231324 app.listen();1325 app.listen(3000);1326 app.listen(3000, 'n.n.n.n');13271328The _port_ argument may also be a string representing the path to a unix domain socket:13291330 app.listen('/tmp/express.sock');13311332Then try it out:13331334 $ telnet /tmp/express.sock1335 GET / HTTP/1.113361337 HTTP/1.1 200 OK1338 Content-Type: text/plain1339 Content-Length: 111340 1341 Hello World