guide.md
This file
Path
docs/guide.md
499 lines · 13.7 KiB · Markdown
Last changed by
Added more view docsTj Holowaychukbefore adoption2f96506
History of this fileTake it
Started guideTj Holowaychukbefore adoption9e3a0c6
line 1why, one step back1Install docsTj Holowaychukbefore adoption63d02f1
lines 2–15why, one step back2### Installation34npm:56 $ npm install express78curl (or similar):910 $ curl -# http://github.com/extjs/Connect/raw/master/install.sh | sh1112git clone or tarball for **HEAD**:1314 $ make install15Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2
line 16why, one step back16### Creating An ApplicationAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 17–18why, one step back1718The _express.Server_ now inherits from _http.Server_, howeverMoved config docs upTj Holowaychukbefore adoption6e8413f
lines 19–20why, one step back19follows the same idiom by providing _express.createServer()_ as shown below. This means20that you can utilize Express server's transparently with other libraries.Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 21–29why, one step back2122 var app = require('express').createServer();23 24 app.get('/', function(req, res){25 res.send('hello world');26 });27 28 app.listen(3000);29Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 30–66why, one step back30### Configuration3132Express supports arbitrary environments, such as _production_ and _development_. Developers33can use the _configure()_ method to setup needs required by the current environment. When34_configure()_ is called without an environment name it will be run in _every_ environment 35prior to the environment specific callback.3637In the example below we only _dumpExceptions_, and respond with exception stack traces38in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.3940 app.configure(function(){41 app.use('/', connect.methodOverride());42 app.use('/', connect.bodyDecoder());43 });44 45 app.configure('development', function(){46 app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));47 });48 49 app.configure('production', function(){50 app.use('/', connect.errorHandler());51 });5253For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5455 app.configure(function(){56 app.set('views', __dirname + '/views');57 app.set('views');58 // => "... views directory ..."59 60 app.enable('some feature');61 // same as app.set('some feature', true);62 63 app.disable('some feature');64 // same as app.set('some feature', false);65 });66More docsTj Holowaychukbefore adoptionde81ee7
lines 67–71why, one step back67To alter the environment we can set the _CONNECT_ENV_ environment variable,68or more specifically _EXPRESS_ENV_, for example:6970 $ EXPRESS_ENV=production node app.js71Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 72–75why, one step back72### Settings7374Express supports the following settings out of the box:75More docsTj Holowaychukbefore adoptionde81ee7
line 76why, one step back76 * _env_ Application environment set internally, use _app.set('env')_ to utilizeInstall docsTj Holowaychukbefore adoption63d02f1
line 77why, one step back77 * _home_ Application base path used with _res.redirect()_Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 78–79why, one step back78 * _views_ Root views directory defaulting to **CWD/views**79 * _view engine_ Default view engine name for views rendered without extensionsAdded more setting docsTj Holowaychukbefore adoption38281e6
line 80why, one step back80 * _reload views_ Reloads altered views, by default watches for _mtime_ changes withFixed reload views exampleTj Holowaychukbefore adoption5fcf971
line 81why, one step back81 with a 5 minute interval. Example: _app.set('reload views', 60000);_Moved config docs upTj Holowaychukbefore adoption6e8413f
line 82why, one step back82Started guideTj Holowaychukbefore adoption9e3a0c6
lines 83–86why, one step back83### Routing8485Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.86For example we may want to render a user's account for the path _/user/12_, thisRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 87–88why, one step back87can be done by defining the route below. The values associated to the named placeholders,88are passed as the _third_ argument, which here we name _params_.Started guideTj Holowaychukbefore adoption9e3a0c6
lines 89–132why, one step back8990 app.get('/user/:id', function(req, res, params){91 res.send('user ' + params.id);92 });9394A route is simple a string which is compiled to a _RegExp_ internally. For example95when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:9697 \/user\/([^\/]+)\/?9899Literal regular expressions may also be passed for complex uses:100101 app.get(/^\/foo(bar)?$/, function(){});102103Below are some route examples, and the associated paths that they104may consume:105106 "/user/:id"107 /user/12108109 "/users/:id?"110 /users/5111 /users112113 "/files/*"114 /files/jquery.js115 /files/javascripts/jquery.js116117 "/file/*.*"118 /files/jquery.js119 /files/javascripts/jquery.js120 121 "/user/:id/:operation?"122 /user/1123 /user/1/edit124 125 "/products.:format"126 /products.json127 /products.xml128129 "/products.:format?"130 /products.json131 /products.xml132 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 133–148why, one step back133134### Passing Route Control135136We may pass control to the next _matching_ route, by calling the _fourth_ parameter,137the _next()_ function. When a match cannot be made, control is passed back to Connect.138139 app.get('/users/:id?', function(req, res, params){140 if (params.id) {141 // do something142 } else {143 next();144 }145 });146 147 app.get('/users', function(req, res, params){148 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 149–163why, one step back149 });150151### Middleware152153The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be154passed to _express.createServer()_ as you would with a regular Connect server. For example:155156 var connect = require('connect'),157 express = require('express');158159 var app = express.createServer(160 connect.logger(),161 connect.bodyDecoder()162 );163Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 164–212why, one step back164Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:165166 app.use('/', connect.logger({ format: ':method :uri' }));167168### Error Handling169170Express provides the _app.error()_ method which receives exceptions thrown within a route,171or passed to _next(err)_. Below is an example which serves different pages based on our172ad-hoc _NotFound_ exception:173174 function NotFound(msg){175 this.name = 'NotFound';176 Error.call(this, msg);177 Error.captureStackTrace(this, arguments.callee);178 }179180 sys.inherits(NotFound, Error);181182 app.get('/404', function(req, res){183 throw new NotFound;184 });185186 app.get('/500', function(req, res){187 throw new Error('keyboard cat!');188 });189190We can call _app.error()_ several times as shown below.191Here we check for an instanceof _NotFound_ and show the192404 page, or we pass on to the next error handler.193194 app.error(function(err, req, res, next){195 if (err instanceof NotFound) {196 res.render('404.jade');197 } else {198 next(err);199 }200 });201202Here we assume all errors as 500 for the simplicity of203this demo, however you can choose whatever you like204205 app.error(function(err, req, res){206 res.render('500.jade', {207 locals: {208 error: err209 } 210 });211 });212Added more view docsTj Holowaychukbefore adoption2f96506
lines 213–256why, one step back213### View Rendering214215View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name216of the module that will be required. For example the view _layout.ejs_ will217tell the view system to _require('ejs')_, the module being loaded must (currently)218export the method _exports.render(str, options)_ to comply with Express, however 219with will likely be extensible in the future.220221Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,222and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 223the _body_ local variable in _layout.haml_.224225 app.get('/', function(req, res){226 res.render('index.haml', {227 locals: { title: 'My Site' }228 });229 });230231### View Partials232233The Express view system has built-in support for partials and collections, which are234sort of "mini" views representing a document fragment. For example rather than iterating235in a view to display comments, we would use a partial with collection support:236237 partial('comment.haml', { collection: comments });238239To make things even less verbose we can assume the extension as _.haml_ when omitted,240however if we wished we could use an ejs partial, within a haml view for example.241242 partial('comment', { collection: comments });243244And once again even further, when rendering a collection we can simply pass245an array, if no other options are desired:246247 partial('comments', comments);248249### Template Engines250251Below are a few template engines commonly used with Express:252253 * [Jade](http://github.com/visionmedia/jade) haml.js successor254 * [Haml](http://github.com/visionmedia/haml.js) indented templates255 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript256More docsTj Holowaychukbefore adoptionde81ee7
line 257why, one step back257### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 258–264why, one step back258259Get the case-insensitive request header _key_, with optional _defaultValue_:260261 req.header('Host');262 req.header('host');263 req.header('Accept', '*/*');264More docsTj Holowaychukbefore adoptionde81ee7
line 265why, one step back265### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 266–288why, one step back266267Check if the _Accept_ header is present, and includes the given _type_.268269When the _Accept_ header is not present _true_ is returned. Otherwise270the given _type_ is matched by an exact match, and then subtypes. You271may pass the subtype such as "html" which is then converted internally272to "text/html" using the mime lookup table.273274 // Accept: text/html275 req.accepts('html');276 // => true277278 // Accept: text/*; application/json279 req.accepts('html');280 req.accepts('text/html');281 req.accepts('text/plain');282 req.accepts('application/json');283 // => true284285 req.accepts('image/png');286 req.accepts('png');287 // => false288More docsTj Holowaychukbefore adoptionde81ee7
line 289why, one step back289### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 290–300why, one step back290291Return the value of param _name_ when present.292293 - Checks route placeholders, ex: /user/:id294 - Checks query string params, ex: ?id=12295 - Checks urlencoded body params, ex: id=12296297To utilize urlencoded request bodies, _req.body_298should be an object. This can be done by using299the _connect.bodyDecoder_ middleware.300More docsTj Holowaychukbefore adoptionde81ee7
line 301why, one step back301### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 302–318why, one step back302303Queue flash _msg_ of the given _type_.304305 req.flash('info', 'email sent');306 req.flash('error', 'email delivery failed');307 req.flash('info', 'email re-sent');308 // => 2309310 req.flash('info');311 // => ['email sent', 'email re-sent']312313 req.flash('info');314 // => []315316 req.flash();317 // => { error: ['email delivery failed'], info: [] }318More docsTj Holowaychukbefore adoptionde81ee7
line 319why, one step back319### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 320–326why, one step back320321Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header322to see if it was issued by an _XMLHttpRequest_:323324 req.xhr325 req.isXMLHttpRequest326More docsTj Holowaychukbefore adoptionde81ee7
line 327why, one step back327### res.header(key[, val])More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 328–339why, one step back328329Get or set the response header _key_.330331 res.header('Content-Length');332 // => undefined333334 res.header('Content-Length', 123);335 // => 123336337 res.header('Content-Length');338 // => 123339More docsTj Holowaychukbefore adoptionde81ee7
line 340why, one step back340### res.contentType(type)More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 341–347why, one step back341342Sets the _Content-Type_ response header to the given _type_.343344 var filename = 'path/to/image.png';345 res.contentType(filename);346 // res.headers['Content-Type'] is now "image/png"347More docsTj Holowaychukbefore adoptionde81ee7
line 348why, one step back348### res.attachment([filename])Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 349–353why, one step back349350Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.351352 res.attachment('path/to/my/image.png');353More docsTj Holowaychukbefore adoptionde81ee7
line 354why, one step back354### res.sendfile(path)Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 355–362why, one step back355356Used by `res.download()` to transfer an arbitrary file. 357358 res.sendfile('path/to/my.file');359360**NOTE**: this is _not_ a replacement for Connect's _staticProvider_ middleware,361nor does it perform any security checks, use with caution when using in a dynamic manor.362More docsTj Holowaychukbefore adoptionde81ee7
line 363why, one step back363### res.download(file[, filename])Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 364–374why, one step back364365Transfer the given _file_ as an attachment with optional alternative _filename_.366367 res.download('path/to/image.png');368 res.download('path/to/image.png', 'foo.png');369370This is equivalent to:371372 res.attachment(file);373 res.sendfile(file);374More docsTj Holowaychukbefore adoptionde81ee7
line 375why, one step back375### res.send(body|status[, headers|status[, status]])Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 376–391why, one step back376377The `res.send()` method is a high level response utility allowing you to pass378objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status379code based responses. The following are all valid uses:380381 res.send(new Buffer('wahoo'));382 res.send({ some: 'json' });383 res.send('<p>some html</p>');384 res.send('Sorry, cant find that', 404);385 res.send('text', { 'Content-Type': 'text/plain' }, 201);386 res.send(404);387388By default the _Content-Type_ response header is set, however if explicitly389assigned through `res.send()` or previously with `res.header()` or `res.contentType()`390it will not be set again.391More docsTj Holowaychukbefore adoptionde81ee7
line 392why, one step back392### res.redirect(url[, status])Added configuration sectionTj Holowaychukbefore adoption83d2555
line 393why, one step back393More docsTj Holowaychukbefore adoptionbedff32
line 394why, one step back394Redirect to the given _url_ with a default response _status_ of 302.Configuration docsTj Holowaychukbefore adoptioncb04364
line 395why, one step back395More docsTj Holowaychukbefore adoptionbedff32
lines 396–405why, one step back396 res.redirect('/', 301);397 res.redirect('/account');398 res.redirect('http://google.com');399 res.redirect('home');400 res.redirect('back');401402Express supports "redirect mapping", which by default provides _home_, and _back_.403The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes404the "home" setting and defaults to "/".405More docsTj Holowaychukbefore adoptionde81ee7
lines 406–443why, one step back406### app.set(name[, val])407408Apply an application level setting _name_ to _val_, or409get the value of _name_ when _val_ is not present:410411 app.set('reload views', 200);412 app.set('reload views');413 // => 200414415### app.enable(name)416417Enable the given setting _name_:418419 app.enable('some arbitrary setting');420 app.set('some arbitrary setting');421 // => true422423### app.disable(name)424425Disable the given setting _name_:426427 app.disable('some setting');428 app.set('some setting');429 // => false430431### app.configure(env|function[, function])432433Define a callback function for the given _env_ (or all environments) with callback _function_:434435 app.configure(function(){436 // executed for each env437 });438439 app.configure('development', function(){440 // executed for 'development' only441 });442443### app.redirect(name, val)More docsTj Holowaychukbefore adoptionbedff32
lines 444–465why, one step back444445For use with `res.redirect()` we can map redirects at the application level as shown below:446447 app.redirect('google', 'http://google.com');448449Now in a route we may call:450451 res.redirect('google');452453We may also map dynamic redirects:454455 app.redirect('comments', function(req, res, params){456 return '/post/' + params.id + '/comments';457 });458459So now we may do the following, and the redirect will dynamically adjust to460the context of the request. If we called this route with _GET /post/12_ our461redirect _Location_ would be _/post/12/comments_.462463 app.get('/post/:id', function(req, res){464 res.redirect('comments');465 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 466–468why, one step back466467### app.error(function)468More error docsTj Holowaychukbefore adoption6227f5c
lines 469–471why, one step back469Adds an error handler _function_ which will receive the exception as the first parameter as shown below.470Note that we may set several error handlers by making several calls to this method, however the handler471should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 472–475why, one step back472473 app.error(function(err, req, res, next){474 res.send(err.message, 500);475 });Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 476–484why, one step back476477### app.listen([port[, host]])478479Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all480connections will be accepted via _INADDR_ANY_.481482 app.listen();483 app.listen(3000);484 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 485–499why, one step back485486The _port_ argument may also be a string representing the path to a unix domain socket:487488 app.listen('/tmp/express.sock');489490Then try it out:491492 $ telnet /tmp/express.sock493 GET / HTTP/1.1494495 HTTP/1.1 200 OK496 Content-Type: text/plain497 Content-Length: 11498 499 Hello World