Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,340 lines · 45.2 KiB · Markdown

Last changed by

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

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–154why, one step back
70
71To alter the environment we can set the _NODE_ENV_ environment variable, for example:7273 $ NODE_ENV=production node app.js7475This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7677### Settings7879Express supports the following settings out of the box:8081 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.82 * _views_ Root views directory defaulting to **CWD/views**83 * _view engine_ Default view engine name for views rendered without extensions84 * _view options_ An object specifying global view options8586### Routing8788Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.89For example we may want to render a user's account for the path _/user/12_, this90can be done by defining the route below. The values associated to the named placeholders 91are available as `req.params`.9293 app.get('/user/:id', function(req, res){94 res.send('user ' + req.params.id);95 });9697A route is simple a string which is compiled to a _RegExp_ internally. For example98when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:99100 \/user\/([^\/]+)\/?101102Regular expression literals may also be passed for complex uses. Since capture103groups 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]_.104105 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){106 res.send(req.params);107 });108109Curl requests against the previously defined route:110111 $ curl http://dev:3000/user112 [null,null]113 $ curl http://dev:3000/users114 [null,null]115 $ curl http://dev:3000/users/1116 ["1",null]117 $ curl http://dev:3000/users/1..15118 ["1","15"]119120Below are some route examples, and the associated paths that they121may consume:122123 "/user/:id"124 /user/12125126 "/users/:id?"127 /users/5128 /users129130 "/files/*"131 /files/jquery.js132 /files/javascripts/jquery.js133134 "/file/*.*"135 /files/jquery.js136 /files/javascripts/jquery.js137 138 "/user/:id/:operation?"139 /user/1140 /user/1/edit141 142 "/products.:format"143 /products.json144 /products.xml145146 "/products.:format?"147 /products.json148 /products.xml149 /products150 151 "/user/:id.:format?"152 /user/12153 /user/12.json154

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 155why, one step back
155For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

markdown escapingTj Holowaychukbefore adoptionf0df843

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 174why, one step back
174and middleware continue to be invoked in the order that they are added via _use()_. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_ and decides to respond.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 189why, one step back
189The _app.all()_ method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to _req.user_.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 249–256why, one step back
249
250### Route Middleware251252Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.253254Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 255256 app.get('/user/:id', function(req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 261–265why, one step back
261 });
262263To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 264265 function loadUser(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 278–282why, one step back
278 });
279280Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.281282 function andRestrictToSelf(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 290–294why, one step back
290 });
291292Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.293294 function andRestrictTo(role) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 304–332why, one step back
304 });
305306Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.307308 var a = [middleware1, middleware2]309 , b = [middleware3, middleware4]310 , all = [a, b];311 312 app.get('/foo', a, function(){});313 app.get('/bar', a, function(){});314 315 app.get('/', a, middleware3, middleware4, function(){});316 app.get('/', a, b, function(){});317 app.get('/', all, function(){});318319For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.320321### HTTP Methods322323We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.324325 A common example for _POST_ usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.326 327 <form method="post" action="/">328 <input type="text" name="user[name]" />329 <input type="text" name="user[email]" />330 <input type="submit" value="Submit" />331 </form>332

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 333why, one step back
333By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 334why, one step back
334

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 344why, one step back
344When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 345why, one step back
345

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 347–368why, one step back
347 app.use(express.methodOverride());
348349The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:350351 <form method="post" action="/">352 <input type="hidden" name="_method" value="put" />353 <input type="text" name="user[name]" />354 <input type="text" name="user[email]" />355 <input type="submit" value="Submit" /> 356 </form>357358 app.put('/', function(){359 console.log(req.body.user);360 res.redirect('back');361 });362363### Error Handling364365Express provides the _app.error()_ method which receives exceptions thrown within a route,366or passed to _next(err)_. Below is an example which serves different pages based on our367ad-hoc _NotFound_ exception:368

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

doc typoTj Holowaychukbefore adoptionfae1ba9

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 403why, one step back
403this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 404why, one step back
404

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 426why, one step back
426

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 427why, one step back
427Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_, we might typically do something like below:

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 436why, one step back
436With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 465–466why, one step back
465tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour
466_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 467why, one step back
467

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 478–496why, one step back
478
479 app.set('view engine', 'jade');480481Allowing us to render with:482483 res.render('index');484485vs:486487 res.render('index.jade');488489When _view engine_ is set, extensions are entirely optional, however we can still490mix and match template engines:491492 res.render('another-page.ejs');493494Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:495496 app.set('view options', {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 497why, one step back
497 layout: false

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 501–524why, one step back
501
502 res.render('myview.ejs', { layout: true });503504When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:505506 res.render('page', { layout: 'mylayout' });507508Otherwise we must specify the extension:509510 res.render('page', { layout: 'mylayout.jade' });511512These paths may also be absolute:513514 res.render('page', { layout: __dirname + '/../../mylayout.jade' });515516A good example of this is specifying custom _ejs_ opening and closing tags:517518 app.set('view options', {519 open: '{{',520 close: '}}'521 });522523### View Partials524

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 541why, one step back
541

note on localsTj Holowaychukbefore adoption022c5e1

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 546–552why, one step back
546__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.
547548### View Lookup549550View 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_.551552The 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 553why, one step back
553

more docsTj Holowaychukbefore adoption0b6a941

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 556–559why, one step back
556### Template Engines
557558Below are a few template engines commonly used with Express:559

Add haml back in docsTj Holowaychukbefore adoptione85752c

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 561–567why, one step back
561 * [Jade](http://jade-lang.com) haml.js successor
562 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript563 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating564 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node565566### Session Support567

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

docsTj Holowaychukbefore adoption5581ca2

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 607why, one step back
607

docsTj Holowaychukbefore adoption4609984

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 618–627why, one step back
618The _Referrer_ and _Referer_ header fields are special-cased, either will work:
619620 // sent Referrer: http://google.com621622 req.header('Referer');623 // => "http://google.com"624625 req.header('Referrer');626 // => "http://google.com"627

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 628–704why, one step back
628### req.accepts(type)
629630Check if the _Accept_ header is present, and includes the given _type_.631632When the _Accept_ header is not present _true_ is returned. Otherwise633the given _type_ is matched by an exact match, and then subtypes. You634may pass the subtype such as "html" which is then converted internally635to "text/html" using the mime lookup table.636637 // Accept: text/html638 req.accepts('html');639 // => true640641 // Accept: text/*; application/json642 req.accepts('html');643 req.accepts('text/html');644 req.accepts('text/plain');645 req.accepts('application/json');646 // => true647648 req.accepts('image/png');649 req.accepts('png');650 // => false651652### req.is(type)653654Check if the incoming request contains the _Content-Type_655header field, and it contains the give mime _type_.656 657 // With Content-Type: text/html; charset=utf-8658 req.is('html');659 req.is('text/html');660 // => true661 662 // When Content-Type is application/json663 req.is('json');664 req.is('application/json');665 // => true666 667 req.is('html');668 // => false669 670Ad-hoc callbacks can also be registered with Express, to perform671assertions again the request, for example if we need an expressive672way to check if our incoming request is an image, we can register _"an image"_673callback:674 675 app.is('an image', function(req){676 return 0 == req.headers['content-type'].indexOf('image');677 });678 679Now within our route callbacks, we can use to to assert content types680such as _"image/jpeg"_, _"image/png"_, etc.681 682 app.post('/image/upload', function(req, res, next){683 if (req.is('an image')) {684 // do something685 } else {686 next();687 }688 });689690Keep in mind this method is _not_ limited to checking _Content-Type_, you691can perform any request assertion you wish.692693Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:694695 req.is('image/*');696697We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.698699 req.is('*/json');700701### req.param(name[, default])702703Return the value of param _name_ when present or _default_.704

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 712–749why, one step back
712
713### req.flash(type[, msg])714715Queue flash _msg_ of the given _type_.716717 req.flash('info', 'email sent');718 req.flash('error', 'email delivery failed');719 req.flash('info', 'email re-sent');720 // => 2721722 req.flash('info');723 // => ['email sent', 'email re-sent']724725 req.flash('info');726 // => []727728 req.flash();729 // => { error: ['email delivery failed'], info: [] }730731Flash notification message may also utilize formatters, by default only the %s string formatter is available:732733 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);734735### req.isXMLHttpRequest736737Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header738to see if it was issued by an _XMLHttpRequest_:739740 req.xhr741 req.isXMLHttpRequest742743### res.header(key[, val])744745Get or set the response header _key_.746747 res.header('Content-Length');748 // => undefined749

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 752why, one step back
752

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for charsetTj Holowaychukbefore adoptiond12452f

lines 756–773why, one step back
756### res.charset
757758Sets 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:759760 res.charset = 'ISO-8859-1';761 res.render('users');762763or before responding with `res.send()`:764765 res.charset = 'ISO-8859-1';766 res.send(str);767768or with node's `res.end()`:769770 res.charset = 'ISO-8859-1';771 res.header('Content-Type', 'text/plain');772 res.end(str);773

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 781why, one step back
781

docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a

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

Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73

lines 786–789why, one step back
786Or simply the extension without leading `.`:
787788 res.contentType('json');789

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 814why, one step back
814

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 815–818why, one step back
815 res.sendfile(path, { bufferSize: 1024 }, function(err){
816 // handle817 });818

docsTj Holowaychukbefore adoption236a412

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 820why, one step back
820

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 821–830why, one step back
821Transfer the given _file_ as an attachment with optional alternative _filename_.
822823 res.download('path/to/image.png');824 res.download('path/to/image.png', 'foo.png');825826This is equivalent to:827828 res.attachment(file);829 res.sendfile(file);830

docsTj Holowaychukbefore adoption236a412

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

docsTj Holowaychukbefore adoption236a412

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for res.cookie()Tj Holowaychukbefore adoption00e1dbf

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

doc typoTj Holowaychukbefore adoption62df63d

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 890why, one step back
890

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 913–948why, one step back
913
914### res.partial(view[, options])915916Render _view_ partial with the given _options_. This method is always available917to the view as a local variable.918919- _object_ the object named by _as_ or derived from the view name920- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.921 * as: 'something' will add the _something_ local variable922 * as: this will use the collection value as the template context923 * as: global will merge the collection value's properties with _locals_924925- _collection_ Array of objects, the name is derived from the view name itself. 926 For example _video.html_ will have a object _video_ available to it.927928The following are equivalent, and the name of collection value when passed929to the partial will be _movie_ as derived from the name.930931 partial('theatre/movie.jade', { collection: movies });932 partial('theatre/movie.jade', movies);933 partial('movie.jade', { collection: movies });934 partial('movie.jade', movies);935 partial('movie', movies);936 // In view: movie.director937938To change the local from _movie_ to _video_ we can use the "as" option:939940 partial('movie', { collection: movies, as: 'video' });941 // In view: video.director942943Also we can make our movie the value of _this_ within our view so that instead944of _movie.director_ we could use _this.director_.945946 partial('movie', { collection: movies, as: this });947 // In view: this.director948

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 950–970why, one step back
950pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:
951952 partial('movie', { collection: movies, as: global });953 // In view: director954955This same logic applies to a single partial object usage:956957 partial('movie', { object: movie, as: this });958 // In view: this.director959960 partial('movie', { object: movie, as: global });961 // In view: director962963 partial('movie', { object: movie, as: 'video' });964 // In view: video.director965966 partial('movie', { object: movie });967 // In view: movie.director968969When 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:970

docs for partial changesTj Holowaychukbefore adoption20b8fac

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

docs for partial changesTj Holowaychukbefore adoption20b8fac

lines 974–984why, one step back
974
975The 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:976977 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 978 partial('movie', movie)979980For 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:981982 partial('movie', { locals: { movie: movie }})983 partial('movie', { movie: movie })984 partial('movie', { object: movie })

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 985why, one step back
985

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 986–1000why, one step back
986This 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:
987988 app.get('/users', function(req, res){989 if (req.xhr) {990 // respond with the each user in the collection991 // passed to the "user" view992 res.partial('user', users);993 } else {994 // respond with layout, and users page995 // which internally does partial('user', users)996 // along with other UI997 res.render('users', { users: users });998 }999 });1000

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1001–1017why, one step back
1001### res.local(name[, val])
10021003Get 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()`.10041005 app.all('/movie/:id', function(req, res, next){1006 Movie.get(req.params.id, function(err, movie){1007 // Assigns res.locals.movie = movie1008 res.local('movie', movie);1009 });1010 });1011 1012 app.get('/movie/:id', function(req, res){1013 // movie is already a local, however we1014 // can pass more if we wish1015 res.render('movie', { displayReviews: true });1016 });1017

doc typoTj Holowaychukbefore adoptionc3e6326

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

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1027–1051why, one step back
1027### app.set(name[, val])
10281029Apply an application level setting _name_ to _val_, or1030get the value of _name_ when _val_ is not present:10311032 app.set('views', __dirname + '/views');1033 app.set('views');1034 // => ...path...10351036Alternatively you may simply access the settings via _app.settings_:10371038 app.settings.views1039 // => ...path...10401041### app.enable(name)10421043Enable the given setting _name_:10441045 app.enable('some arbitrary setting');1046 app.set('some arbitrary setting');1047 // => true10481049 app.enabled('some arbitrary setting');1050 // => true1051

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1052–1062why, one step back
1052### app.enabled(name)
10531054Check if setting _name_ is enabled:10551056 app.enabled('view cache');1057 // => false10581059 app.enable('view cache');1060 app.enabled('view cache');1061 // => true1062

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1063–1073why, one step back
1063### app.disable(name)
10641065Disable the given setting _name_:10661067 app.disable('some setting');1068 app.set('some setting');1069 // => false1070 1071 app.disabled('some setting');1072 // => false1073

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1074–1086why, one step back
1074### app.disabled(name)
10751076Check if setting _name_ is disabled:10771078 app.enable('view cache');10791080 app.disabled('view cache');1081 // => false10821083 app.disable('view cache');1084 app.disabled('view cache');1085 // => true1086

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1087–1100why, one step back
1087### app.configure(env|function[, function])
10881089Define a callback function for the given _env_ (or all environments) with callback _function_:10901091 app.configure(function(){1092 // executed for each env1093 });10941095 app.configure('development', function(){1096 // executed for 'development' only1097 });10981099### app.redirect(name, val)1100

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1136–1140why, one step back
1136
1137### app.helpers(obj)11381139Registers static view helpers.1140

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

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

docs for "filename" localTj Holowaychukbefore adoptionbf06d90

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

docsTj Holowaychukbefore adoption885fb1f

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

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

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1159–1167why, one step back
1159
1160### app.dynamicHelpers(obj)11611162Registers dynamic view helpers. Dynamic view helpers1163are simply functions which accept _req_, _res_, and are1164evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1165becomes the local variable it is associated with.11661167 app.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lines 1196–1212why, one step back
1196 // => [Function]
11971198 app.lookup.put('/user/:id');1199 // => [Function]12001201 app.lookup.all('/user/:id');1202 // => [Function, Function]12031204 app.lookup.all('/hey');1205 // => []12061207 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1208 without a callback, as a shortcut, for example the following are1209 equivalent:1210 1211 app.lookup.get('/user');1212 app.get('/user');

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

line 1213why, one step back
1213

more docsTj Holowaychukbefore adoption6230ec5

lines 1214–1229why, one step back
1214 Each function returned has the following properties:
1215 1216 var fn = app.get('/user/:id/:op?')[0];12171218 fn.regexp1219 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12201221 fn.keys1222 // => ['id', 'op']12231224 fn.path1225 // => '/user/:id/:op?'12261227 fn.method1228 // => 'GET'1229

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

lines 1230–1257why, one step back
1230### app.match
12311232 The _app.match_ http methods return an array of callback functions1233 which match the given _url_, which may include a query string etc. This1234 is useful when you want reflect on which routes have the opportunity to1235 respond.12361237 Suppose we define the following routes:12381239 app.get('/user/:id', function(){});1240 app.put('/user/:id', function(){});1241 app.get('/user/:id/:op?', function(){});12421243 Our match against __GET__ will return two functions, since the _:op_1244 in our second route is optional.12451246 app.match.get('/user/1');1247 // => [Function, Function]12481249 This second call returns only the callback for _/user/:id/:op?_.12501251 app.match.get('/user/23/edit');1252 // => [Function]12531254 We can also use _all()_ to disregard the http method:12551256 app.match.all('/user/20');1257 // => [Function, Function, Function]

more docsTj Holowaychukbefore adoption6230ec5

lines 1258–1270why, one step back
1258
1259 Each function matched has the following properties:1260 1261 var fn = app.match.get('/user/23/edit')[0];12621263 fn.keys1264 // => ['id', 'op']12651266 fn.params1267 // => { id: '23', op: 'edit' }12681269 fn.method1270 // => 'GET'

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

line 1271why, one step back
1271

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1282–1301why, one step back
1282 });
1283 1284 app.use(blog);12851286### app.register(ext, exports)12871288Register the given template engine _exports_1289as _ext_. For example we may wish to map ".html"1290files to jade:12911292 app.register('.html', require('jade'));12931294This is also useful for libraries that may not1295match extensions correctly. For example my haml.js1296library is installed from npm as "hamljs" so instead1297of layout.hamljs, we can register the engine as ".haml":12981299 app.register('.haml', require('haml-js'));13001301For engines that do not comply with the Express

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

line 1306why, one step back
1306

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

connect >= 1.0.1Tj Holowaychukbefore adoption4c95031

lines 1317–1340why, one step back
1317
1318### app.listen([port[, host]])13191320Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1321connections will be accepted via _INADDR_ANY_.13221323 app.listen();1324 app.listen(3000);1325 app.listen(3000, 'n.n.n.n');13261327The _port_ argument may also be a string representing the path to a unix domain socket:13281329 app.listen('/tmp/express.sock');13301331Then try it out:13321333 $ telnet /tmp/express.sock1334 GET / HTTP/1.113351336 HTTP/1.1 200 OK1337 Content-Type: text/plain1338 Content-Length: 111339 1340 Hello World