guide.md
This file
Path
docs/guide.md
455 lines · 12.0 KiB · Markdown
Last changed by
Unix domain socket docsTj Holowaychukbefore adoption2fa7907
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 });212More docsTj Holowaychukbefore adoptionde81ee7
line 213why, one step back213### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 214–220why, one step back214215Get the case-insensitive request header _key_, with optional _defaultValue_:216217 req.header('Host');218 req.header('host');219 req.header('Accept', '*/*');220More docsTj Holowaychukbefore adoptionde81ee7
line 221why, one step back221### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 222–244why, one step back222223Check if the _Accept_ header is present, and includes the given _type_.224225When the _Accept_ header is not present _true_ is returned. Otherwise226the given _type_ is matched by an exact match, and then subtypes. You227may pass the subtype such as "html" which is then converted internally228to "text/html" using the mime lookup table.229230 // Accept: text/html231 req.accepts('html');232 // => true233234 // Accept: text/*; application/json235 req.accepts('html');236 req.accepts('text/html');237 req.accepts('text/plain');238 req.accepts('application/json');239 // => true240241 req.accepts('image/png');242 req.accepts('png');243 // => false244More docsTj Holowaychukbefore adoptionde81ee7
line 245why, one step back245### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 246–256why, one step back246247Return the value of param _name_ when present.248249 - Checks route placeholders, ex: /user/:id250 - Checks query string params, ex: ?id=12251 - Checks urlencoded body params, ex: id=12252253To utilize urlencoded request bodies, _req.body_254should be an object. This can be done by using255the _connect.bodyDecoder_ middleware.256More docsTj Holowaychukbefore adoptionde81ee7
line 257why, one step back257### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 258–274why, one step back258259Queue flash _msg_ of the given _type_.260261 req.flash('info', 'email sent');262 req.flash('error', 'email delivery failed');263 req.flash('info', 'email re-sent');264 // => 2265266 req.flash('info');267 // => ['email sent', 'email re-sent']268269 req.flash('info');270 // => []271272 req.flash();273 // => { error: ['email delivery failed'], info: [] }274More docsTj Holowaychukbefore adoptionde81ee7
line 275why, one step back275### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 276–282why, one step back276277Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header278to see if it was issued by an _XMLHttpRequest_:279280 req.xhr281 req.isXMLHttpRequest282More docsTj Holowaychukbefore adoptionde81ee7
line 283why, one step back283### res.header(key[, val])More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 284–295why, one step back284285Get or set the response header _key_.286287 res.header('Content-Length');288 // => undefined289290 res.header('Content-Length', 123);291 // => 123292293 res.header('Content-Length');294 // => 123295More docsTj Holowaychukbefore adoptionde81ee7
line 296why, one step back296### res.contentType(type)More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 297–303why, one step back297298Sets the _Content-Type_ response header to the given _type_.299300 var filename = 'path/to/image.png';301 res.contentType(filename);302 // res.headers['Content-Type'] is now "image/png"303More docsTj Holowaychukbefore adoptionde81ee7
line 304why, one step back304### res.attachment([filename])Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 305–309why, one step back305306Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.307308 res.attachment('path/to/my/image.png');309More docsTj Holowaychukbefore adoptionde81ee7
line 310why, one step back310### res.sendfile(path)Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 311–318why, one step back311312Used by `res.download()` to transfer an arbitrary file. 313314 res.sendfile('path/to/my.file');315316**NOTE**: this is _not_ a replacement for Connect's _staticProvider_ middleware,317nor does it perform any security checks, use with caution when using in a dynamic manor.318More docsTj Holowaychukbefore adoptionde81ee7
line 319why, one step back319### res.download(file[, filename])Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 320–330why, one step back320321Transfer the given _file_ as an attachment with optional alternative _filename_.322323 res.download('path/to/image.png');324 res.download('path/to/image.png', 'foo.png');325326This is equivalent to:327328 res.attachment(file);329 res.sendfile(file);330More docsTj Holowaychukbefore adoptionde81ee7
line 331why, one step back331### res.send(body|status[, headers|status[, status]])Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 332–347why, one step back332333The `res.send()` method is a high level response utility allowing you to pass334objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status335code based responses. The following are all valid uses:336337 res.send(new Buffer('wahoo'));338 res.send({ some: 'json' });339 res.send('<p>some html</p>');340 res.send('Sorry, cant find that', 404);341 res.send('text', { 'Content-Type': 'text/plain' }, 201);342 res.send(404);343344By default the _Content-Type_ response header is set, however if explicitly345assigned through `res.send()` or previously with `res.header()` or `res.contentType()`346it will not be set again.347More docsTj Holowaychukbefore adoptionde81ee7
line 348why, one step back348### res.redirect(url[, status])Added configuration sectionTj Holowaychukbefore adoption83d2555
line 349why, one step back349More docsTj Holowaychukbefore adoptionbedff32
line 350why, one step back350Redirect to the given _url_ with a default response _status_ of 302.Configuration docsTj Holowaychukbefore adoptioncb04364
line 351why, one step back351More docsTj Holowaychukbefore adoptionbedff32
lines 352–361why, one step back352 res.redirect('/', 301);353 res.redirect('/account');354 res.redirect('http://google.com');355 res.redirect('home');356 res.redirect('back');357358Express supports "redirect mapping", which by default provides _home_, and _back_.359The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes360the "home" setting and defaults to "/".361More docsTj Holowaychukbefore adoptionde81ee7
lines 362–399why, one step back362### app.set(name[, val])363364Apply an application level setting _name_ to _val_, or365get the value of _name_ when _val_ is not present:366367 app.set('reload views', 200);368 app.set('reload views');369 // => 200370371### app.enable(name)372373Enable the given setting _name_:374375 app.enable('some arbitrary setting');376 app.set('some arbitrary setting');377 // => true378379### app.disable(name)380381Disable the given setting _name_:382383 app.disable('some setting');384 app.set('some setting');385 // => false386387### app.configure(env|function[, function])388389Define a callback function for the given _env_ (or all environments) with callback _function_:390391 app.configure(function(){392 // executed for each env393 });394395 app.configure('development', function(){396 // executed for 'development' only397 });398399### app.redirect(name, val)More docsTj Holowaychukbefore adoptionbedff32
lines 400–421why, one step back400401For use with `res.redirect()` we can map redirects at the application level as shown below:402403 app.redirect('google', 'http://google.com');404405Now in a route we may call:406407 res.redirect('google');408409We may also map dynamic redirects:410411 app.redirect('comments', function(req, res, params){412 return '/post/' + params.id + '/comments';413 });414415So now we may do the following, and the redirect will dynamically adjust to416the context of the request. If we called this route with _GET /post/12_ our417redirect _Location_ would be _/post/12/comments_.418419 app.get('/post/:id', function(req, res){420 res.redirect('comments');421 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 422–424why, one step back422423### app.error(function)424More error docsTj Holowaychukbefore adoption6227f5c
lines 425–427why, one step back425Adds an error handler _function_ which will receive the exception as the first parameter as shown below.426Note that we may set several error handlers by making several calls to this method, however the handler427should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 428–431why, one step back428429 app.error(function(err, req, res, next){430 res.send(err.message, 500);431 });Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 432–440why, one step back432433### app.listen([port[, host]])434435Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all436connections will be accepted via _INADDR_ANY_.437438 app.listen();439 app.listen(3000);440 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 441–455why, one step back441442The _port_ argument may also be a string representing the path to a unix domain socket:443444 app.listen('/tmp/express.sock');445446Then try it out:447448 $ telnet /tmp/express.sock449 GET / HTTP/1.1450451 HTTP/1.1 200 OK452 Content-Type: text/plain453 Content-Length: 11454 455 Hello World