guide.md
This file
Path
docs/guide.md
315 lines · 8.8 KiB · Markdown
Last changed by
More docsTj Holowaychukbefore adoptiondfecbe5
History of this fileTake it
Started guideTj Holowaychukbefore adoption9e3a0c6
line 1why, one step back1Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2
line 2why, one step back2### Creating An ApplicationAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 3–4why, one step back34The _express.Server_ now inherits from _http.Server_, howeverMoved config docs upTj Holowaychukbefore adoption6e8413f
lines 5–6why, one step back5follows the same idiom by providing _express.createServer()_ as shown below. This means6that you can utilize Express server's transparently with other libraries.Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 7–15why, one step back78 var app = require('express').createServer();9 10 app.get('/', function(req, res){11 res.send('hello world');12 });13 14 app.listen(3000);15Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 16–56why, one step back16### Configuration1718Express supports arbitrary environments, such as _production_ and _development_. Developers19can use the _configure()_ method to setup needs required by the current environment. When20_configure()_ is called without an environment name it will be run in _every_ environment 21prior to the environment specific callback.2223In the example below we only _dumpExceptions_, and respond with exception stack traces24in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.2526 app.configure(function(){27 app.use('/', connect.methodOverride());28 app.use('/', connect.bodyDecoder());29 });30 31 app.configure('development', function(){32 app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));33 });34 35 app.configure('production', function(){36 app.use('/', connect.errorHandler());37 });3839For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:4041 app.configure(function(){42 app.set('views', __dirname + '/views');43 app.set('views');44 // => "... views directory ..."45 46 app.enable('some feature');47 // same as app.set('some feature', true);48 49 app.disable('some feature');50 // same as app.set('some feature', false);51 });5253### Settings5455Express supports the following settings out of the box:56More docsTj Holowaychukbefore adoptionbedff32
line 57why, one step back57 * _home_ Application base path used with `res.redirect()`Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 58–59why, one step back58 * _views_ Root views directory defaulting to **CWD/views**59 * _view engine_ Default view engine name for views rendered without extensionsAdded more setting docsTj Holowaychukbefore adoption38281e6
lines 60–61why, one step back60 * _reload views_ Reloads altered views, by default watches for _mtime_ changes with61 with a 5 minute interval. Example: `app.set('reload views', { interval: 60000 });`Moved config docs upTj Holowaychukbefore adoption6e8413f
line 62why, one step back62Started guideTj Holowaychukbefore adoption9e3a0c6
lines 63–66why, one step back63### Routing6465Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.66For example we may want to render a user's account for the path _/user/12_, thisRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 67–68why, one step back67can be done by defining the route below. The values associated to the named placeholders,68are passed as the _third_ argument, which here we name _params_.Started guideTj Holowaychukbefore adoption9e3a0c6
lines 69–112why, one step back6970 app.get('/user/:id', function(req, res, params){71 res.send('user ' + params.id);72 });7374A route is simple a string which is compiled to a _RegExp_ internally. For example75when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:7677 \/user\/([^\/]+)\/?7879Literal regular expressions may also be passed for complex uses:8081 app.get(/^\/foo(bar)?$/, function(){});8283Below are some route examples, and the associated paths that they84may consume:8586 "/user/:id"87 /user/128889 "/users/:id?"90 /users/591 /users9293 "/files/*"94 /files/jquery.js95 /files/javascripts/jquery.js9697 "/file/*.*"98 /files/jquery.js99 /files/javascripts/jquery.js100 101 "/user/:id/:operation?"102 /user/1103 /user/1/edit104 105 "/products.:format"106 /products.json107 /products.xml108109 "/products.:format?"110 /products.json111 /products.xml112 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 113–128why, one step back113114### Passing Route Control115116We may pass control to the next _matching_ route, by calling the _fourth_ parameter,117the _next()_ function. When a match cannot be made, control is passed back to Connect.118119 app.get('/users/:id?', function(req, res, params){120 if (params.id) {121 // do something122 } else {123 next();124 }125 });126 127 app.get('/users', function(req, res, params){128 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 129–143why, one step back129 });130131### Middleware132133The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be134passed to _express.createServer()_ as you would with a regular Connect server. For example:135136 var connect = require('connect'),137 express = require('express');138139 var app = express.createServer(140 connect.logger(),141 connect.bodyDecoder()142 );143More docsTj Holowaychukbefore adoptiondfecbe5
lines 144–213why, one step back144### ServerRequest#header(key[, defaultValue])145146Get the case-insensitive request header _key_, with optional _defaultValue_:147148 req.header('Host');149 req.header('host');150 req.header('Accept', '*/*');151152### ServerRequest#accepts(type)153154Check if the _Accept_ header is present, and includes the given _type_.155156When the _Accept_ header is not present _true_ is returned. Otherwise157the given _type_ is matched by an exact match, and then subtypes. You158may pass the subtype such as "html" which is then converted internally159to "text/html" using the mime lookup table.160161 // Accept: text/html162 req.accepts('html');163 // => true164165 // Accept: text/*; application/json166 req.accepts('html');167 req.accepts('text/html');168 req.accepts('text/plain');169 req.accepts('application/json');170 // => true171172 req.accepts('image/png');173 req.accepts('png');174 // => false175176### ServerRequest#param(name)177178Return the value of param _name_ when present.179180 - Checks route placeholders, ex: /user/:id181 - Checks query string params, ex: ?id=12182 - Checks urlencoded body params, ex: id=12183184To utilize urlencoded request bodies, _req.body_185should be an object. This can be done by using186the _connect.bodyDecoder_ middleware.187188### ServerRequest#flash(type[, msg])189190Queue flash _msg_ of the given _type_.191192 req.flash('info', 'email sent');193 req.flash('error', 'email delivery failed');194 req.flash('info', 'email re-sent');195 // => 2196197 req.flash('info');198 // => ['email sent', 'email re-sent']199200 req.flash('info');201 // => []202203 req.flash();204 // => { error: ['email delivery failed'], info: [] }205206### ServerRequest#isXMLHttpRequest207208Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header209to see if it was issued by an _XMLHttpRequest_:210211 req.xhr212 req.isXMLHttpRequest213More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 214–234why, one step back214### ServerResponse#header(key[, val])215216Get or set the response header _key_.217218 res.header('Content-Length');219 // => undefined220221 res.header('Content-Length', 123);222 // => 123223224 res.header('Content-Length');225 // => 123226227### ServerResponse#contentType(type)228229Sets the _Content-Type_ response header to the given _type_.230231 var filename = 'path/to/image.png';232 res.contentType(filename);233 // res.headers['Content-Type'] is now "image/png"234Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 235–240why, one step back235### ServerResponse#attachment([filename])236237Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.238239 res.attachment('path/to/my/image.png');240Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 241–261why, one step back241### ServerResponse#sendfile(path)242243Used by `res.download()` to transfer an arbitrary file. 244245 res.sendfile('path/to/my.file');246247**NOTE**: this is _not_ a replacement for Connect's _staticProvider_ middleware,248nor does it perform any security checks, use with caution when using in a dynamic manor.249250### ServerResponse#download(file[, filename])251252Transfer the given _file_ as an attachment with optional alternative _filename_.253254 res.download('path/to/image.png');255 res.download('path/to/image.png', 'foo.png');256257This is equivalent to:258259 res.attachment(file);260 res.sendfile(file);261Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 262–278why, one step back262### ServerRequest#send(body|status[, headers|status[, status]])263264The `res.send()` method is a high level response utility allowing you to pass265objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status266code based responses. The following are all valid uses:267268 res.send(new Buffer('wahoo'));269 res.send({ some: 'json' });270 res.send('<p>some html</p>');271 res.send('Sorry, cant find that', 404);272 res.send('text', { 'Content-Type': 'text/plain' }, 201);273 res.send(404);274275By default the _Content-Type_ response header is set, however if explicitly276assigned through `res.send()` or previously with `res.header()` or `res.contentType()`277it will not be set again.278More docsTj Holowaychukbefore adoptionbedff32
line 279why, one step back279### ServerResponse#redirect(url[, status])Added configuration sectionTj Holowaychukbefore adoption83d2555
line 280why, one step back280More docsTj Holowaychukbefore adoptionbedff32
line 281why, one step back281Redirect to the given _url_ with a default response _status_ of 302.Configuration docsTj Holowaychukbefore adoptioncb04364
line 282why, one step back282More docsTj Holowaychukbefore adoptionbedff32
lines 283–315why, one step back283 res.redirect('/', 301);284 res.redirect('/account');285 res.redirect('http://google.com');286 res.redirect('home');287 res.redirect('back');288289Express supports "redirect mapping", which by default provides _home_, and _back_.290The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes291the "home" setting and defaults to "/".292293### Server#redirect(name, val)294295For use with `res.redirect()` we can map redirects at the application level as shown below:296297 app.redirect('google', 'http://google.com');298299Now in a route we may call:300301 res.redirect('google');302303We may also map dynamic redirects:304305 app.redirect('comments', function(req, res, params){306 return '/post/' + params.id + '/comments';307 });308309So now we may do the following, and the redirect will dynamically adjust to310the context of the request. If we called this route with _GET /post/12_ our311redirect _Location_ would be _/post/12/comments_.312313 app.get('/post/:id', function(req, res){314 res.redirect('comments');315 });