guide.md
This file
Path
docs/guide.md
329 lines · 9.0 KiB · Markdown
Last changed by
Install docsTj Holowaychukbefore adoption63d02f1
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–70why, 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 });6667### Settings6869Express supports the following settings out of the box:70Install docsTj Holowaychukbefore adoption63d02f1
line 71why, one step back71 * _home_ Application base path used with _res.redirect()_Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 72–73why, one step back72 * _views_ Root views directory defaulting to **CWD/views**73 * _view engine_ Default view engine name for views rendered without extensionsAdded more setting docsTj Holowaychukbefore adoption38281e6
lines 74–75why, one step back74 * _reload views_ Reloads altered views, by default watches for _mtime_ changes with75 with a 5 minute interval. Example: `app.set('reload views', { interval: 60000 });`Moved config docs upTj Holowaychukbefore adoption6e8413f
line 76why, one step back76Started guideTj Holowaychukbefore adoption9e3a0c6
lines 77–80why, one step back77### Routing7879Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.80For example we may want to render a user's account for the path _/user/12_, thisRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 81–82why, one step back81can be done by defining the route below. The values associated to the named placeholders,82are passed as the _third_ argument, which here we name _params_.Started guideTj Holowaychukbefore adoption9e3a0c6
lines 83–126why, one step back8384 app.get('/user/:id', function(req, res, params){85 res.send('user ' + params.id);86 });8788A route is simple a string which is compiled to a _RegExp_ internally. For example89when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:9091 \/user\/([^\/]+)\/?9293Literal regular expressions may also be passed for complex uses:9495 app.get(/^\/foo(bar)?$/, function(){});9697Below are some route examples, and the associated paths that they98may consume:99100 "/user/:id"101 /user/12102103 "/users/:id?"104 /users/5105 /users106107 "/files/*"108 /files/jquery.js109 /files/javascripts/jquery.js110111 "/file/*.*"112 /files/jquery.js113 /files/javascripts/jquery.js114 115 "/user/:id/:operation?"116 /user/1117 /user/1/edit118 119 "/products.:format"120 /products.json121 /products.xml122123 "/products.:format?"124 /products.json125 /products.xml126 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 127–142why, one step back127128### Passing Route Control129130We may pass control to the next _matching_ route, by calling the _fourth_ parameter,131the _next()_ function. When a match cannot be made, control is passed back to Connect.132133 app.get('/users/:id?', function(req, res, params){134 if (params.id) {135 // do something136 } else {137 next();138 }139 });140 141 app.get('/users', function(req, res, params){142 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 143–157why, one step back143 });144145### Middleware146147The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be148passed to _express.createServer()_ as you would with a regular Connect server. For example:149150 var connect = require('connect'),151 express = require('express');152153 var app = express.createServer(154 connect.logger(),155 connect.bodyDecoder()156 );157More docsTj Holowaychukbefore adoptiondfecbe5
lines 158–227why, one step back158### ServerRequest#header(key[, defaultValue])159160Get the case-insensitive request header _key_, with optional _defaultValue_:161162 req.header('Host');163 req.header('host');164 req.header('Accept', '*/*');165166### ServerRequest#accepts(type)167168Check if the _Accept_ header is present, and includes the given _type_.169170When the _Accept_ header is not present _true_ is returned. Otherwise171the given _type_ is matched by an exact match, and then subtypes. You172may pass the subtype such as "html" which is then converted internally173to "text/html" using the mime lookup table.174175 // Accept: text/html176 req.accepts('html');177 // => true178179 // Accept: text/*; application/json180 req.accepts('html');181 req.accepts('text/html');182 req.accepts('text/plain');183 req.accepts('application/json');184 // => true185186 req.accepts('image/png');187 req.accepts('png');188 // => false189190### ServerRequest#param(name)191192Return the value of param _name_ when present.193194 - Checks route placeholders, ex: /user/:id195 - Checks query string params, ex: ?id=12196 - Checks urlencoded body params, ex: id=12197198To utilize urlencoded request bodies, _req.body_199should be an object. This can be done by using200the _connect.bodyDecoder_ middleware.201202### ServerRequest#flash(type[, msg])203204Queue flash _msg_ of the given _type_.205206 req.flash('info', 'email sent');207 req.flash('error', 'email delivery failed');208 req.flash('info', 'email re-sent');209 // => 2210211 req.flash('info');212 // => ['email sent', 'email re-sent']213214 req.flash('info');215 // => []216217 req.flash();218 // => { error: ['email delivery failed'], info: [] }219220### ServerRequest#isXMLHttpRequest221222Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header223to see if it was issued by an _XMLHttpRequest_:224225 req.xhr226 req.isXMLHttpRequest227More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 228–248why, one step back228### ServerResponse#header(key[, val])229230Get or set the response header _key_.231232 res.header('Content-Length');233 // => undefined234235 res.header('Content-Length', 123);236 // => 123237238 res.header('Content-Length');239 // => 123240241### ServerResponse#contentType(type)242243Sets the _Content-Type_ response header to the given _type_.244245 var filename = 'path/to/image.png';246 res.contentType(filename);247 // res.headers['Content-Type'] is now "image/png"248Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 249–254why, one step back249### ServerResponse#attachment([filename])250251Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.252253 res.attachment('path/to/my/image.png');254Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 255–275why, one step back255### ServerResponse#sendfile(path)256257Used by `res.download()` to transfer an arbitrary file. 258259 res.sendfile('path/to/my.file');260261**NOTE**: this is _not_ a replacement for Connect's _staticProvider_ middleware,262nor does it perform any security checks, use with caution when using in a dynamic manor.263264### ServerResponse#download(file[, filename])265266Transfer the given _file_ as an attachment with optional alternative _filename_.267268 res.download('path/to/image.png');269 res.download('path/to/image.png', 'foo.png');270271This is equivalent to:272273 res.attachment(file);274 res.sendfile(file);275Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 276–292why, one step back276### ServerRequest#send(body|status[, headers|status[, status]])277278The `res.send()` method is a high level response utility allowing you to pass279objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status280code based responses. The following are all valid uses:281282 res.send(new Buffer('wahoo'));283 res.send({ some: 'json' });284 res.send('<p>some html</p>');285 res.send('Sorry, cant find that', 404);286 res.send('text', { 'Content-Type': 'text/plain' }, 201);287 res.send(404);288289By default the _Content-Type_ response header is set, however if explicitly290assigned through `res.send()` or previously with `res.header()` or `res.contentType()`291it will not be set again.292More docsTj Holowaychukbefore adoptionbedff32
line 293why, one step back293### ServerResponse#redirect(url[, status])Added configuration sectionTj Holowaychukbefore adoption83d2555
line 294why, one step back294More docsTj Holowaychukbefore adoptionbedff32
line 295why, one step back295Redirect to the given _url_ with a default response _status_ of 302.Configuration docsTj Holowaychukbefore adoptioncb04364
line 296why, one step back296More docsTj Holowaychukbefore adoptionbedff32
lines 297–329why, one step back297 res.redirect('/', 301);298 res.redirect('/account');299 res.redirect('http://google.com');300 res.redirect('home');301 res.redirect('back');302303Express supports "redirect mapping", which by default provides _home_, and _back_.304The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes305the "home" setting and defaults to "/".306307### Server#redirect(name, val)308309For use with `res.redirect()` we can map redirects at the application level as shown below:310311 app.redirect('google', 'http://google.com');312313Now in a route we may call:314315 res.redirect('google');316317We may also map dynamic redirects:318319 app.redirect('comments', function(req, res, params){320 return '/post/' + params.id + '/comments';321 });322323So now we may do the following, and the redirect will dynamically adjust to324the context of the request. If we called this route with _GET /post/12_ our325redirect _Location_ would be _/post/12/comments_.326327 app.get('/post/:id', function(req, res){328 res.redirect('comments');329 });