guide.md
This file
Path
docs/guide.md
224 lines · 6.4 KiB · Markdown
Last changed by
Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
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 docs :)Tj Holowaychukbefore adoption0c5fe61
lines 144–164why, one step back144### ServerResponse#header(key[, val])145146Get or set the response header _key_.147148 res.header('Content-Length');149 // => undefined150151 res.header('Content-Length', 123);152 // => 123153154 res.header('Content-Length');155 // => 123156157### ServerResponse#contentType(type)158159Sets the _Content-Type_ response header to the given _type_.160161 var filename = 'path/to/image.png';162 res.contentType(filename);163 // res.headers['Content-Type'] is now "image/png"164Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 165–170why, one step back165### ServerResponse#attachment([filename])166167Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.168169 res.attachment('path/to/my/image.png');170Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 171–187why, one step back171### ServerRequest#send(body|status[, headers|status[, status]])172173The `res.send()` method is a high level response utility allowing you to pass174objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status175code based responses. The following are all valid uses:176177 res.send(new Buffer('wahoo'));178 res.send({ some: 'json' });179 res.send('<p>some html</p>');180 res.send('Sorry, cant find that', 404);181 res.send('text', { 'Content-Type': 'text/plain' }, 201);182 res.send(404);183184By default the _Content-Type_ response header is set, however if explicitly185assigned through `res.send()` or previously with `res.header()` or `res.contentType()`186it will not be set again.187More docsTj Holowaychukbefore adoptionbedff32
line 188why, one step back188### ServerResponse#redirect(url[, status])Added configuration sectionTj Holowaychukbefore adoption83d2555
line 189why, one step back189More docsTj Holowaychukbefore adoptionbedff32
line 190why, one step back190Redirect to the given _url_ with a default response _status_ of 302.Configuration docsTj Holowaychukbefore adoptioncb04364
line 191why, one step back191More docsTj Holowaychukbefore adoptionbedff32
lines 192–224why, one step back192 res.redirect('/', 301);193 res.redirect('/account');194 res.redirect('http://google.com');195 res.redirect('home');196 res.redirect('back');197198Express supports "redirect mapping", which by default provides _home_, and _back_.199The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes200the "home" setting and defaults to "/".201202### Server#redirect(name, val)203204For use with `res.redirect()` we can map redirects at the application level as shown below:205206 app.redirect('google', 'http://google.com');207208Now in a route we may call:209210 res.redirect('google');211212We may also map dynamic redirects:213214 app.redirect('comments', function(req, res, params){215 return '/post/' + params.id + '/comments';216 });217218So now we may do the following, and the redirect will dynamically adjust to219the context of the request. If we called this route with _GET /post/12_ our220redirect _Location_ would be _/post/12/comments_.221222 app.get('/post/:id', function(req, res){223 res.redirect('comments');224 });