Skip to content
Myr

guide.md

This file

Path

docs/guide.md

531 lines · 15.1 KiB · Markdown

Last changed by

More view docsTj Holowaychukbefore adoption1c8ff48

History of this file

Take it

Started guideTj Holowaychukbefore adoption9e3a0c6

line 1why, one step back
1

Install docsTj Holowaychukbefore adoption63d02f1

lines 2–5why, one step back
2### Installation
34npm:5

Updated install docsTj Holowaychukbefore adoption193c4a9

line 6why, one step back
6 $ npm install connect

Install docsTj Holowaychukbefore adoption63d02f1

lines 7–10why, one step back
7 $ npm install express
89curl (or similar):10

Updated install docsTj Holowaychukbefore adoption193c4a9

line 11why, one step back
11 $ curl -# http://github.com/visionmedia/express/raw/master/install.sh | sh

Install docsTj Holowaychukbefore adoption63d02f1

line 12why, one step back
12

Updated install docsTj Holowaychukbefore adoption193c4a9

line 13why, one step back
13git clone, first update the submodules:

Install docsTj Holowaychukbefore adoption63d02f1

line 14why, one step back
14

Updated install docsTj Holowaychukbefore adoption193c4a9

line 15why, one step back
15 $ git submodule update --init

Install docsTj Holowaychukbefore adoption63d02f1

line 16why, one step back
16 $ make install

Updated install docsTj Holowaychukbefore adoption193c4a9

line 17why, one step back
17 $ make install-support

Install docsTj Holowaychukbefore adoption63d02f1

line 18why, one step back
18

Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2

line 19why, one step back
19### Creating An Application

Added configuration sectionTj Holowaychukbefore adoption83d2555

lines 20–21why, one step back
20
21The _express.Server_ now inherits from _http.Server_, however

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 22–23why, one step back
22follows the same idiom by providing _express.createServer()_ as shown below. This means
23that you can utilize Express server's transparently with other libraries.

Added configuration sectionTj Holowaychukbefore adoption83d2555

lines 24–32why, one step back
24
25 var app = require('express').createServer();26 27 app.get('/', function(req, res){28 res.send('hello world');29 });30 31 app.listen(3000);32

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 33–69why, one step back
33### Configuration
3435Express supports arbitrary environments, such as _production_ and _development_. Developers36can use the _configure()_ method to setup needs required by the current environment. When37_configure()_ is called without an environment name it will be run in _every_ environment 38prior to the environment specific callback.3940In the example below we only _dumpExceptions_, and respond with exception stack traces41in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.4243 app.configure(function(){44 app.use('/', connect.methodOverride());45 app.use('/', connect.bodyDecoder());46 });47 48 app.configure('development', function(){49 app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));50 });51 52 app.configure('production', function(){53 app.use('/', connect.errorHandler());54 });5556For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5758 app.configure(function(){59 app.set('views', __dirname + '/views');60 app.set('views');61 // => "... views directory ..."62 63 app.enable('some feature');64 // same as app.set('some feature', true);65 66 app.disable('some feature');67 // same as app.set('some feature', false);68 });69

More docsTj Holowaychukbefore adoptionde81ee7

lines 70–74why, one step back
70To alter the environment we can set the _CONNECT_ENV_ environment variable,
71or more specifically _EXPRESS_ENV_, for example:7273 $ EXPRESS_ENV=production node app.js74

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 75–78why, one step back
75### Settings
7677Express supports the following settings out of the box:78

More docsTj Holowaychukbefore adoptionde81ee7

line 79why, one step back
79 * _env_ Application environment set internally, use _app.set('env')_ to utilize

Install docsTj Holowaychukbefore adoption63d02f1

line 80why, one step back
80 * _home_ Application base path used with _res.redirect()_

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 81–82why, one step back
81 * _views_ Root views directory defaulting to **CWD/views**
82 * _view engine_ Default view engine name for views rendered without extensions

Added more setting docsTj Holowaychukbefore adoption38281e6

line 83why, one step back
83 * _reload views_ Reloads altered views, by default watches for _mtime_ changes with

Fixed reload views exampleTj Holowaychukbefore adoption5fcf971

line 84why, one step back
84 with a 5 minute interval. Example: _app.set('reload views', 60000);_

Moved config docs upTj Holowaychukbefore adoption6e8413f

line 85why, one step back
85

Started guideTj Holowaychukbefore adoption9e3a0c6

lines 86–89why, one step back
86### Routing
8788Express 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_, this

Route passing docsTj Holowaychukbefore adoption0ace97c

lines 90–91why, one step back
90can be done by defining the route below. The values associated to the named placeholders,
91are passed as the _third_ argument, which here we name _params_.

Started guideTj Holowaychukbefore adoption9e3a0c6

lines 92–135why, one step back
92
93 app.get('/user/:id', function(req, res, params){94 res.send('user ' + 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\/([^\/]+)\/?101102Literal regular expressions may also be passed for complex uses:103104 app.get(/^\/foo(bar)?$/, function(){});105106Below are some route examples, and the associated paths that they107may consume:108109 "/user/:id"110 /user/12111112 "/users/:id?"113 /users/5114 /users115116 "/files/*"117 /files/jquery.js118 /files/javascripts/jquery.js119120 "/file/*.*"121 /files/jquery.js122 /files/javascripts/jquery.js123 124 "/user/:id/:operation?"125 /user/1126 /user/1/edit127 128 "/products.:format"129 /products.json130 /products.xml131132 "/products.:format?"133 /products.json134 /products.xml135 /products

Route passing docsTj Holowaychukbefore adoption0ace97c

lines 136–151why, one step back
136
137### Passing Route Control138139We may pass control to the next _matching_ route, by calling the _fourth_ parameter,140the _next()_ function. When a match cannot be made, control is passed back to Connect.141142 app.get('/users/:id?', function(req, res, params){143 if (params.id) {144 // do something145 } else {146 next();147 }148 });149 150 app.get('/users', function(req, res, params){151 // do something else

Added configuration sectionTj Holowaychukbefore adoption83d2555

lines 152–166why, one step back
152 });
153154### Middleware155156The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be157passed to _express.createServer()_ as you would with a regular Connect server. For example:158159 var connect = require('connect'),160 express = require('express');161162 var app = express.createServer(163 connect.logger(),164 connect.bodyDecoder()165 );166

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 167–215why, one step back
167Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:
168169 app.use('/', connect.logger({ format: ':method :uri' }));170171### Error Handling172173Express provides the _app.error()_ method which receives exceptions thrown within a route,174or passed to _next(err)_. Below is an example which serves different pages based on our175ad-hoc _NotFound_ exception:176177 function NotFound(msg){178 this.name = 'NotFound';179 Error.call(this, msg);180 Error.captureStackTrace(this, arguments.callee);181 }182183 sys.inherits(NotFound, Error);184185 app.get('/404', function(req, res){186 throw new NotFound;187 });188189 app.get('/500', function(req, res){190 throw new Error('keyboard cat!');191 });192193We can call _app.error()_ several times as shown below.194Here we check for an instanceof _NotFound_ and show the195404 page, or we pass on to the next error handler.196197 app.error(function(err, req, res, next){198 if (err instanceof NotFound) {199 res.render('404.jade');200 } else {201 next(err);202 }203 });204205Here we assume all errors as 500 for the simplicity of206this demo, however you can choose whatever you like207208 app.error(function(err, req, res){209 res.render('500.jade', {210 locals: {211 error: err212 } 213 });214 });215

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 216–229why, one step back
216Our apps could also utilize the Connect _errorHandler_ middleware
217to report on exceptions. For example if we wish to output exceptions 218in "development" mode to _stderr_ we can use:219220 app.use('/', connect.errorHandler({ dumpExceptions: true }));221222Also during development we may want fancy html pages to show exceptions223that are passed or thrown, so we can set _showStack_ to true:224225 app.use('/', connect.errorHandler({ showStack: true, dumpExceptions: true }));226227The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_228is present, which is useful for developing apps that rely heavily on client-side JavaScript.229

Added more view docsTj Holowaychukbefore adoption2f96506

lines 230–273why, one step back
230### View Rendering
231232View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name233of the module that will be required. For example the view _layout.ejs_ will234tell the view system to _require('ejs')_, the module being loaded must (currently)235export the method _exports.render(str, options)_ to comply with Express, however 236with will likely be extensible in the future.237238Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,239and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 240the _body_ local variable in _layout.haml_.241242 app.get('/', function(req, res){243 res.render('index.haml', {244 locals: { title: 'My Site' }245 });246 });247248### View Partials249250The Express view system has built-in support for partials and collections, which are251sort of "mini" views representing a document fragment. For example rather than iterating252in a view to display comments, we would use a partial with collection support:253254 partial('comment.haml', { collection: comments });255256To make things even less verbose we can assume the extension as _.haml_ when omitted,257however if we wished we could use an ejs partial, within a haml view for example.258259 partial('comment', { collection: comments });260261And once again even further, when rendering a collection we can simply pass262an array, if no other options are desired:263264 partial('comments', comments);265266### Template Engines267268Below are a few template engines commonly used with Express:269270 * [Jade](http://github.com/visionmedia/jade) haml.js successor271 * [Haml](http://github.com/visionmedia/haml.js) indented templates272 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript273

More docsTj Holowaychukbefore adoptionde81ee7

line 274why, one step back
274### req.header(key[, defaultValue])

More docsTj Holowaychukbefore adoptiondfecbe5

lines 275–281why, one step back
275
276Get the case-insensitive request header _key_, with optional _defaultValue_:277278 req.header('Host');279 req.header('host');280 req.header('Accept', '*/*');281

More docsTj Holowaychukbefore adoptionde81ee7

line 282why, one step back
282### req.accepts(type)

More docsTj Holowaychukbefore adoptiondfecbe5

lines 283–305why, one step back
283
284Check if the _Accept_ header is present, and includes the given _type_.285286When the _Accept_ header is not present _true_ is returned. Otherwise287the given _type_ is matched by an exact match, and then subtypes. You288may pass the subtype such as "html" which is then converted internally289to "text/html" using the mime lookup table.290291 // Accept: text/html292 req.accepts('html');293 // => true294295 // Accept: text/*; application/json296 req.accepts('html');297 req.accepts('text/html');298 req.accepts('text/plain');299 req.accepts('application/json');300 // => true301302 req.accepts('image/png');303 req.accepts('png');304 // => false305

More docsTj Holowaychukbefore adoptionde81ee7

line 306why, one step back
306### req.param(name)

More docsTj Holowaychukbefore adoptiondfecbe5

lines 307–317why, one step back
307
308Return the value of param _name_ when present.309310 - Checks route placeholders, ex: /user/:id311 - Checks query string params, ex: ?id=12312 - Checks urlencoded body params, ex: id=12313314To utilize urlencoded request bodies, _req.body_315should be an object. This can be done by using316the _connect.bodyDecoder_ middleware.317

More docsTj Holowaychukbefore adoptionde81ee7

line 318why, one step back
318### req.flash(type[, msg])

More docsTj Holowaychukbefore adoptiondfecbe5

lines 319–335why, one step back
319
320Queue flash _msg_ of the given _type_.321322 req.flash('info', 'email sent');323 req.flash('error', 'email delivery failed');324 req.flash('info', 'email re-sent');325 // => 2326327 req.flash('info');328 // => ['email sent', 'email re-sent']329330 req.flash('info');331 // => []332333 req.flash();334 // => { error: ['email delivery failed'], info: [] }335

More docsTj Holowaychukbefore adoptionde81ee7

line 336why, one step back
336### req.isXMLHttpRequest

More docsTj Holowaychukbefore adoptiondfecbe5

lines 337–343why, one step back
337
338Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header339to see if it was issued by an _XMLHttpRequest_:340341 req.xhr342 req.isXMLHttpRequest343

More docsTj Holowaychukbefore adoptionde81ee7

line 344why, one step back
344### res.header(key[, val])

More docs :)Tj Holowaychukbefore adoption0c5fe61

lines 345–356why, one step back
345
346Get or set the response header _key_.347348 res.header('Content-Length');349 // => undefined350351 res.header('Content-Length', 123);352 // => 123353354 res.header('Content-Length');355 // => 123356

More docsTj Holowaychukbefore adoptionde81ee7

line 357why, one step back
357### res.contentType(type)

More docs :)Tj Holowaychukbefore adoption0c5fe61

lines 358–364why, one step back
358
359Sets the _Content-Type_ response header to the given _type_.360361 var filename = 'path/to/image.png';362 res.contentType(filename);363 // res.headers['Content-Type'] is now "image/png"364

More docsTj Holowaychukbefore adoptionde81ee7

line 365why, one step back
365### res.attachment([filename])

Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1

lines 366–370why, one step back
366
367Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.368369 res.attachment('path/to/my/image.png');370

More docsTj Holowaychukbefore adoptionde81ee7

line 371why, one step back
371### res.sendfile(path)

Docs for new res methodsTj Holowaychukbefore adoptionb08dab9

lines 372–377why, one step back
372
373Used by `res.download()` to transfer an arbitrary file. 374375 res.sendfile('path/to/my.file');376377**NOTE**: this is _not_ a replacement for Connect's _staticProvider_ middleware,

Fixed doc typoTj Holowaychukbefore adoptione742da2

line 378why, one step back
378nor does it perform any security checks, use with caution when using in a dynamic manner.

Docs for new res methodsTj Holowaychukbefore adoptionb08dab9

line 379why, one step back
379

More docsTj Holowaychukbefore adoptionde81ee7

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

Docs for new res methodsTj Holowaychukbefore adoptionb08dab9

lines 381–391why, one step back
381
382Transfer the given _file_ as an attachment with optional alternative _filename_.383384 res.download('path/to/image.png');385 res.download('path/to/image.png', 'foo.png');386387This is equivalent to:388389 res.attachment(file);390 res.sendfile(file);391

More docsTj Holowaychukbefore adoptionde81ee7

line 392why, one step back
392### res.send(body|status[, headers|status[, status]])

Docs for res.send()Tj Holowaychukbefore adoption5a48248

lines 393–408why, one step back
393
394The `res.send()` method is a high level response utility allowing you to pass395objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status396code based responses. The following are all valid uses:397398 res.send(new Buffer('wahoo'));399 res.send({ some: 'json' });400 res.send('<p>some html</p>');401 res.send('Sorry, cant find that', 404);402 res.send('text', { 'Content-Type': 'text/plain' }, 201);403 res.send(404);404405By default the _Content-Type_ response header is set, however if explicitly406assigned through `res.send()` or previously with `res.header()` or `res.contentType()`407it will not be set again.408

More docsTj Holowaychukbefore adoptionde81ee7

line 409why, one step back
409### res.redirect(url[, status])

Added configuration sectionTj Holowaychukbefore adoption83d2555

line 410why, one step back
410

More docsTj Holowaychukbefore adoptionbedff32

line 411why, one step back
411Redirect to the given _url_ with a default response _status_ of 302.

Configuration docsTj Holowaychukbefore adoptioncb04364

line 412why, one step back
412

More docsTj Holowaychukbefore adoptionbedff32

lines 413–422why, one step back
413 res.redirect('/', 301);
414 res.redirect('/account');415 res.redirect('http://google.com');416 res.redirect('home');417 res.redirect('back');418419Express supports "redirect mapping", which by default provides _home_, and _back_.420The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes421the "home" setting and defaults to "/".422

More view docsTj Holowaychukbefore adoption1c8ff48

lines 423–437why, one step back
423### res.render(view[, options[, fn]])
424425Render _view_ with the given _options_ and optional callback _fn_.426When a callback function is given a response will _not_ be made427automatically, however otherwise a response of _200_ and _text/html_ is given.428429 Most engines accept one or more of the following options,430 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:431432 - _context|scope_ Template evaluation context (_this_)433 - _locals_ Object containing local variables434 - _filename_ Filename used for the _cache_ option435 - _cache_ Cache intermediate JavaScript in memory436 - _debug_ Output debugging information437

More docsTj Holowaychukbefore adoptionde81ee7

lines 438–475why, one step back
438### app.set(name[, val])
439440Apply an application level setting _name_ to _val_, or441get the value of _name_ when _val_ is not present:442443 app.set('reload views', 200);444 app.set('reload views');445 // => 200446447### app.enable(name)448449Enable the given setting _name_:450451 app.enable('some arbitrary setting');452 app.set('some arbitrary setting');453 // => true454455### app.disable(name)456457Disable the given setting _name_:458459 app.disable('some setting');460 app.set('some setting');461 // => false462463### app.configure(env|function[, function])464465Define a callback function for the given _env_ (or all environments) with callback _function_:466467 app.configure(function(){468 // executed for each env469 });470471 app.configure('development', function(){472 // executed for 'development' only473 });474475### app.redirect(name, val)

More docsTj Holowaychukbefore adoptionbedff32

lines 476–497why, one step back
476
477For use with `res.redirect()` we can map redirects at the application level as shown below:478479 app.redirect('google', 'http://google.com');480481Now in a route we may call:482483 res.redirect('google');484485We may also map dynamic redirects:486487 app.redirect('comments', function(req, res, params){488 return '/post/' + params.id + '/comments';489 });490491So now we may do the following, and the redirect will dynamically adjust to492the context of the request. If we called this route with _GET /post/12_ our493redirect _Location_ would be _/post/12/comments_.494495 app.get('/post/:id', function(req, res){496 res.redirect('comments');497 });

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 498–500why, one step back
498
499### app.error(function)500

More error docsTj Holowaychukbefore adoption6227f5c

lines 501–503why, one step back
501Adds an error handler _function_ which will receive the exception as the first parameter as shown below.
502Note that we may set several error handlers by making several calls to this method, however the handler503should call _next(err)_ if it does not wish to deal with the exception:

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 504–507why, one step back
504
505 app.error(function(err, req, res, next){506 res.send(err.message, 500);507 });

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

lines 508–516why, one step back
508
509### app.listen([port[, host]])510511Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all512connections will be accepted via _INADDR_ANY_.513514 app.listen();515 app.listen(3000);516 app.listen(3000, 'n.n.n.n');

Unix domain socket docsTj Holowaychukbefore adoption2fa7907

lines 517–531why, one step back
517
518The _port_ argument may also be a string representing the path to a unix domain socket:519520 app.listen('/tmp/express.sock');521522Then try it out:523524 $ telnet /tmp/express.sock525 GET / HTTP/1.1526527 HTTP/1.1 200 OK528 Content-Type: text/plain529 Content-Length: 11530 531 Hello World