guide.md
This file
Path
docs/guide.md
1,370 lines · 48.0 KiB · Markdown
Last changed by
Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa
History of this fileTake it
The walk stopped after 200 commits: lines older than b5579b6 point at it.
Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1–48why, one step back1### Installation23 $ npm install express45### Creating A Server67 To create an instance of the _express.HTTPServer_, simply invoke the _createServer()_ method. With our instance _app_ we can then define routes based on the HTTP verbs, in this example _app.get()_.89 var app = require('express').createServer();10 11 app.get('/', function(req, res){12 res.send('hello world');13 });14 15 app.listen(3000);1617### Creating An HTTPS Server1819 To initialize a _express.HTTPSServer_ we do the same as above, however we20 pass an options object, accepting _key_, _cert_ and the others mentioned in node's [https documentation](http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer).21 22 var app = require('express').createServer({ key: ... });2324### Configuration2526Express supports arbitrary environments, such as _production_ and _development_. Developers27can use the _configure()_ method to setup needs required by the current environment. When28_configure()_ is called without an environment name it will be run in _every_ environment 29prior to the environment specific callback.3031In the example below we only _dumpExceptions_, and respond with exception stack traces32in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.33Note the use of _app.router_, which can (optionally) be used to mount the application routes,34otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.3536 app.configure(function(){37 app.use(express.methodOverride());38 app.use(express.bodyParser());39 app.use(app.router);40 });41 42 app.configure('development', function(){43 app.use(express.static(__dirname + '/public'));44 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));45 });46 47 app.configure('production', function(){48 var oneYear = 31557600000;Docs for staticProvider() changesTj Holowaychukbefore adoption3cacf05
line 49why, one step back49 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 50–83why, one step back50 app.use(express.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 // => "/absolute/path/to/views"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 66 app.enabled('some feature')67 // => false68 });6970To alter the environment we can set the _NODE_ENV_ environment variable, for example:7172 $ NODE_ENV=production node app.js7374This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7576### Settings7778Express supports the following settings out of the box:7980 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.81 * _views_ Root views directory defaulting to **CWD/views**82 * _view engine_ Default view engine name for views rendered without extensions83 * _view options_ An object specifying global view optionsdocs for "view cache" settingTj Holowaychukbefore adoption805b9ac
line 84why, one step back84 * _view cache_ Enable view caching (enabled in production)Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd
line 85why, one step back85 * _case sensitive routes_ Enable case-sensitive routingAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 86–168why, one step back8687### Routing8889Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.90For example we may want to render a user's account for the path _/user/12_, this91can be done by defining the route below. The values associated to the named placeholders 92are available as `req.params`.9394 app.get('/user/:id', function(req, res){95 res.send('user ' + req.params.id);96 });9798A route is simple a string which is compiled to a _RegExp_ internally. For example99when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:100101 \/user\/([^\/]+)\/?102103Regular expression literals may also be passed for complex uses. Since capture104groups with literal _RegExp_'s are anonymous we can access them directly `req.params`. So our first capture group would be _req.params[0]_ and the second would follow as _req.params[1]_.105106 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){107 res.send(req.params);108 });109110Curl requests against the previously defined route:111112 $ curl http://dev:3000/user113 [null,null]114 $ curl http://dev:3000/users115 [null,null]116 $ curl http://dev:3000/users/1117 ["1",null]118 $ curl http://dev:3000/users/1..15119 ["1","15"]120121Below are some route examples, and the associated paths that they122may consume:123124 "/user/:id"125 /user/12126127 "/users/:id?"128 /users/5129 /users130131 "/files/*"132 /files/jquery.js133 /files/javascripts/jquery.js134135 "/file/*.*"136 /files/jquery.js137 /files/javascripts/jquery.js138 139 "/user/:id/:operation?"140 /user/1141 /user/1/edit142 143 "/products.:format"144 /products.json145 /products.xml146147 "/products.:format?"148 /products.json149 /products.xml150 /products151 152 "/user/:id.:format?"153 /user/12154 /user/12.json155156For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:157158 var express = require('express')159 , app = express.createServer();160161 app.use(express.bodyParser());162163 app.post('/', function(req, res){164 res.send(req.body);165 });166167 app.listen(3000);168docsTj Holowaychukbefore adoption6106188
line 169why, one step back169Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use _'/user/:id([0-9]+)'_ which will _not_ match unless the placeholder value contains only digits.Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 170–237why, one step back170171### Passing Route Control172173We may pass control to the next _matching_ route, by calling the _third_ argument,174the _next()_ function. When a match cannot be made, control is passed back to Connect,175and middleware continue to be invoked in the order that they are added via _use()_. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_ and decides to respond.176177 app.get('/users/:id?', function(req, res, next){178 var id = req.params.id;179 if (id) {180 // do something181 } else {182 next();183 }184 });185 186 app.get('/users', function(req, res){187 // do something else188 });189190The _app.all()_ method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to _req.user_.191192 var express = require('express')193 , app = express.createServer();194195 var users = [{ name: 'tj' }];196197 app.all('/user/:id/:op?', function(req, res, next){198 req.user = users[req.params.id];199 if (req.user) {200 next();201 } else {202 next(new Error('cannot find user ' + req.params.id));203 }204 });205206 app.get('/user/:id', function(req, res){207 res.send('viewing ' + req.user.name);208 });209210 app.get('/user/:id/edit', function(req, res){211 res.send('editing ' + req.user.name);212 });213214 app.put('/user/:id', function(req, res){215 res.send('updating ' + req.user.name);216 });217218 app.get('*', function(req, res){219 res.send('what???', 404);220 });221222 app.listen(3000); 223224### Middleware225226Middleware via [Connect](http://github.com/senchalabs/connect) can be227passed to _express.createServer()_ as you would with a regular Connect server. For example:228229 var express = require('express');230231 var app = express.createServer(232 express.logger()233 , express.bodyParser()234 );235236Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.237Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa
line 238why, one step back238 app.use(express.logger({ format: ':method :url' }));Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 239–250why, one step back239240Typically with connect middleware you would _require('connect')_ like so:241242 var connect = require('connect');243 app.use(connect.logger());244 app.use(connect.bodyParser());245246This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:247248 app.use(express.logger());249 app.use(express.bodyParser());250added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
lines 251–277why, one step back251Middleware ordering is important, when Connect receives a request the _first_ middleware we pass to _createServer()_ or _use()_ is executed with three parameters, _request_, _response_, and a callback function usually named _next_. When _next()_ is invoked the second middleware will then have it's turn and so on. This is important to note because many middleware depend on each other, for example _methodOverride()_ checks _req.body._method_ for the HTTP method override, however _bodyParser()_ parses the request body and populates _req.body_. Another example of this is cookie parsing and session support, we must first _use()_ _cookieParser()_ followed by _session()_.252253Many Express applications may contain the line _app.use(app.router)_, while this may appear strange, it's simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the _last_ middleware so that any exception passed to _next()_ will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below254255 app.use(express.logger(...));256 app.use(express.bodyParser(...));257 app.use(express.cookieParser(...));258 app.use(express.session(...));259 app.use(app.router);260 app.use(express.static(...));261 app.use(express.errorHandler(...));262263First we add _logger()_ so that it may wrap node's _req.end()_ method, providing us with response-time data. Next the request's body will be parsed (if any), followed by cookie parsing and session support, meaning _req.session_ will be defined by the time we hit our routes in _app.router_. If a request such as _GET /javascripts/jquery.js_ is handled by our routes, and we do not call _next()_ then the _static()_ middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.264265 var downloads = {};266267 app.use(app.router);268 app.use(express.static(__dirname + '/public'));269270 app.get('/*', function(req, res, next){271 var file = req.params[0];272 downloads[file] = downloads[file] || 0;273 downloads[file]++;274 next();275 });276277Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 278–348why, one step back278### Route Middleware279280Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.281282Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 283284 app.get('/user/:id', function(req, res, next){285 loadUser(req.params.id, function(err, user){286 if (err) return next(err);287 res.send('Viewing user ' + user.name);288 });289 });290291To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 292293 function loadUser(req, res, next) {294 // You would fetch your user from the db295 var user = users[req.params.id];296 if (user) {297 req.user = user;298 next();299 } else {300 next(new Error('Failed to load user ' + req.params.id));301 }302 }303 304 app.get('/user/:id', loadUser, function(req, res){305 res.send('Viewing user ' + req.user.name);306 });307308Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.309310 function andRestrictToSelf(req, res, next) {311 req.authenticatedUser.id == req.user.id312 ? next()313 : next(new Error('Unauthorized'));314 }315 316 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){317 res.send('Editing user ' + req.user.name);318 });319320Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.321322 function andRestrictTo(role) {323 return function(req, res, next) {324 req.authenticatedUser.role == role325 ? next()326 : next(new Error('Unauthorized'));327 }328 }329 330 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){331 res.send('Deleted user ' + req.user.name);332 });333334Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.335336 var a = [middleware1, middleware2]337 , b = [middleware3, middleware4]338 , all = [a, b];339 340 app.get('/foo', a, function(){});341 app.get('/bar', a, function(){});342 343 app.get('/', a, middleware3, middleware4, function(){});344 app.get('/', a, b, function(){});345 app.get('/', all, function(){});346347For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.348docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 349–350why, one step back349There are times when we may want to "skip" passed remaining route middleware, but continue matching subsequent routes. To do this we invoke `next()` with the string "route" `next('route')`. If no remaining routes match the request url then Express will respond with 404 Not Found.350Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 351–404why, one step back351### HTTP Methods352353We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.354355 A common example for _POST_ usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.356 357 <form method="post" action="/">358 <input type="text" name="user[name]" />359 <input type="text" name="user[email]" />360 <input type="submit" value="Submit" />361 </form>362363By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:364365 app.use(express.bodyParser());366367Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.368369 app.post('/', function(req, res){370 console.log(req.body.user);371 res.redirect('back');372 });373374When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.375376 app.use(express.bodyParser());377 app.use(express.methodOverride());378379The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:380381 <form method="post" action="/">382 <input type="hidden" name="_method" value="put" />383 <input type="text" name="user[name]" />384 <input type="text" name="user[email]" />385 <input type="submit" value="Submit" /> 386 </form>387388 app.put('/', function(){389 console.log(req.body.user);390 res.redirect('back');391 });392393### Error Handling394395Express provides the _app.error()_ method which receives exceptions thrown within a route,396or passed to _next(err)_. Below is an example which serves different pages based on our397ad-hoc _NotFound_ exception:398399 function NotFound(msg){400 this.name = 'NotFound';401 Error.call(this, msg);402 Error.captureStackTrace(this, arguments.callee);403 }404 doc typoTj Holowaychukbefore adoptionfae1ba9
line 405why, one step back405 NotFound.prototype.__proto__ = Error.prototype;Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 406–555why, one step back406 407 app.get('/404', function(req, res){408 throw new NotFound;409 });410 411 app.get('/500', function(req, res){412 throw new Error('keyboard cat!');413 });414415We can call _app.error()_ several times as shown below.416Here we check for an instanceof _NotFound_ and show the417404 page, or we pass on to the next error handler.418419Note that these handlers can be defined anywhere, as they420will be placed below the route handlers on _listen()_. This 421allows for definition within _configure()_ blocks so we can422handle exceptions in different ways based on the environment.423424 app.error(function(err, req, res, next){425 if (err instanceof NotFound) {426 res.render('404.jade');427 } else {428 next(err);429 }430 });431432Here we assume all errors as 500 for the simplicity of433this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.434435 app.error(function(err, req, res){436 res.render('500.jade', {437 error: err438 });439 });440441Our apps could also utilize the Connect _errorHandler_ middleware442to report on exceptions. For example if we wish to output exceptions 443in "development" mode to _stderr_ we can use:444445 app.use(express.errorHandler({ dumpExceptions: true }));446447Also during development we may want fancy html pages to show exceptions448that are passed or thrown, so we can set _showStack_ to true:449450 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));451452The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_453is present, which is useful for developing apps that rely heavily on client-side JavaScript.454455### Route Param Pre-conditions456457Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_, we might typically do something like below:458459 app.get('/user/:userId', function(req, res, next){460 User.get(req.params.userId, function(err, user){461 if (err) return next(err);462 res.send('user ' + user.name);463 });464 }); 465466With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.467468 app.param('userId', function(req, res, next, id){469 User.get(id, function(err, user){470 if (err) return next(err);471 if (!user) return next(new Error('failed to find user'));472 req.user = user;473 next();474 });475 });476477Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:478479 app.get('/user/:userId', function(req, res){480 res.send('user ' + req.user.name);481 });482483For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to _next(err)_.484485 app.param('number', function(n){ return parseInt(n, 10); });486487We may also apply the same callback to several placeholders, for example a route GET _/commits/:from-:to_ are both numbers, so we may define them as an array:488489 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });490491### View Rendering492493View filenames take the form "<name>.<engine>", where <engine> is the name494of the module that will be required. For example the view _layout.ejs_ will495tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour496_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.497498Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,499and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 500the _body_ local variable in _layout.jade_.501502 app.get('/', function(req, res){503 res.render('index.jade', { title: 'My Site' });504 });505506The new _view engine_ setting allows us to specify our default template engine,507so for example when using jade we could set:508509 app.set('view engine', 'jade');510511Allowing us to render with:512513 res.render('index');514515vs:516517 res.render('index.jade');518519When _view engine_ is set, extensions are entirely optional, however we can still520mix and match template engines:521522 res.render('another-page.ejs');523524Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:525526 app.set('view options', {527 layout: false528 });529530Which can then be overridden within the _res.render()_ call if need be:531532 res.render('myview.ejs', { layout: true });533534When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:535536 res.render('page', { layout: 'mylayout' });537538Otherwise we must specify the extension:539540 res.render('page', { layout: 'mylayout.jade' });541542These paths may also be absolute:543544 res.render('page', { layout: __dirname + '/../../mylayout.jade' });545546A good example of this is specifying custom _ejs_ opening and closing tags:547548 app.set('view options', {549 open: '{{',550 close: '}}'551 });552553### View Partials554555The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iteratingdocs for partial changesTj Holowaychukbefore adoption20b8fac
line 556why, one step back556in a view to display comments, we could use partial collection:Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 557–559why, one step back557558 partial('comment', { collection: comments });559docs for partial changesTj Holowaychukbefore adoption20b8fac
line 560why, one step back560If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 561–563why, one step back561562 partial('comment', comments);563docs for partial changesTj Holowaychukbefore adoption20b8fac
line 564why, one step back564When using the partial collection support a few "magic" locals are providedAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 565–785why, one step back565for free:566567 * _firstInCollection_ true if this is the first object568 * _indexInCollection_ index of the object in the collection569 * _lastInCollection_ true if this is the last object570 * _collectionLength_ length of the collection571572Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with _partial('blog/post', post)_ it would generate the _post_ local, but the view calling this function had the local _user_, it would be available to the _blog/post_ view as well.573574For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).575576__NOTE:__ be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.577578### View Lookup579580View lookup is performed relative to the parent view, for example if we had a page view named _views/user/list.jade_, and within that view we did _partial('edit')_ it would attempt to load _views/user/edit.jade_, whereas _partial('../messages')_ would load _views/messages.jade_.581582The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have _res.render('users')_ either _views/users.jade_, or _views/users/index.jade_.583584When utilizing index views as shown above, we may reference _views/users/index.jade_ from a view in the same directory by _partial('users')_, and the view system will try _../users/index_, preventing us from needing to call _partial('index')_.585586### Template Engines587588Below are a few template engines commonly used with Express:589590 * [Haml](http://github.com/visionmedia/haml.js) haml implementation591 * [Jade](http://jade-lang.com) haml.js successor592 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript593 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating594 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node595596### Session Support597598Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.599600 app.use(express.cookieParser());601 app.use(express.session({ secret: "keyboard cat" }));602603By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:604605 var RedisStore = require('connect-redis');606 app.use(express.cookieParser());607 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));608609Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:610611 var RedisStore = require('connect-redis');612 app.use(express.bodyParser());613 app.use(express.cookieParser());614 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));615616 app.post('/add-to-cart', function(req, res){617 // Perhaps we posted several items with a form618 // (use the bodyParser() middleware for this)619 var items = req.body.items;620 req.session.items = items;621 res.redirect('back');622 });623624 app.get('/add-to-cart', function(req, res){625 // When redirected back to GET /add-to-cart626 // we could check req.session.items && req.session.items.length627 // to print out a message628 if (req.session.items && req.session.items.length) {629 req.flash('info', 'You have %s items in your cart', req.session.items.length);630 }631 res.render('shopping-cart');632 });633634The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/middleware-session.html) documentation.635636### Migration Guide637638 Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.639640### req.header(key[, defaultValue])641642Get the case-insensitive request header _key_, with optional _defaultValue_:643644 req.header('Host');645 req.header('host');646 req.header('Accept', '*/*');647648The _Referrer_ and _Referer_ header fields are special-cased, either will work:649650 // sent Referrer: http://google.com651652 req.header('Referer');653 // => "http://google.com"654655 req.header('Referrer');656 // => "http://google.com"657658### req.accepts(type)659660Check if the _Accept_ header is present, and includes the given _type_.661662When the _Accept_ header is not present _true_ is returned. Otherwise663the given _type_ is matched by an exact match, and then subtypes. You664may pass the subtype such as "html" which is then converted internally665to "text/html" using the mime lookup table.666667 // Accept: text/html668 req.accepts('html');669 // => true670671 // Accept: text/*; application/json672 req.accepts('html');673 req.accepts('text/html');674 req.accepts('text/plain');675 req.accepts('application/json');676 // => true677678 req.accepts('image/png');679 req.accepts('png');680 // => false681682### req.is(type)683684Check if the incoming request contains the _Content-Type_685header field, and it contains the give mime _type_.686 687 // With Content-Type: text/html; charset=utf-8688 req.is('html');689 req.is('text/html');690 // => true691 692 // When Content-Type is application/json693 req.is('json');694 req.is('application/json');695 // => true696 697 req.is('html');698 // => false699 700Ad-hoc callbacks can also be registered with Express, to perform701assertions again the request, for example if we need an expressive702way to check if our incoming request is an image, we can register _"an image"_703callback:704 705 app.is('an image', function(req){706 return 0 == req.headers['content-type'].indexOf('image');707 });708 709Now within our route callbacks, we can use to to assert content types710such as _"image/jpeg"_, _"image/png"_, etc.711 712 app.post('/image/upload', function(req, res, next){713 if (req.is('an image')) {714 // do something715 } else {716 next();717 }718 });719720Keep in mind this method is _not_ limited to checking _Content-Type_, you721can perform any request assertion you wish.722723Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:724725 req.is('image/*');726727We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.728729 req.is('*/json');730731### req.param(name[, default])732733Return the value of param _name_ when present or _default_.734735 - Checks route params (_req.params_), ex: /user/:id736 - Checks query string params (_req.query_), ex: ?id=12737 - Checks urlencoded body params (_req.body_), ex: id=12738739To utilize urlencoded request bodies, _req.body_740should be an object. This can be done by using741the _express.bodyParser middleware.742743### req.flash(type[, msg])744745Queue flash _msg_ of the given _type_.746747 req.flash('info', 'email sent');748 req.flash('error', 'email delivery failed');749 req.flash('info', 'email re-sent');750 // => 2751752 req.flash('info');753 // => ['email sent', 'email re-sent']754755 req.flash('info');756 // => []757758 req.flash();759 // => { error: ['email delivery failed'], info: [] }760761Flash notification message may also utilize formatters, by default only the %s string formatter is available:762763 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);764765### req.isXMLHttpRequest766767Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header768to see if it was issued by an _XMLHttpRequest_:769770 req.xhr771 req.isXMLHttpRequest772773### res.header(key[, val])774775Get or set the response header _key_.776777 res.header('Content-Length');778 // => undefined779780 res.header('Content-Length', 123);781 // => 123782 783 res.header('Content-Length');784 // => 123785docs for charsetTj Holowaychukbefore adoptiond12452f
lines 786–803why, one step back786### res.charset787788Sets the charset for subsequent `Content-Type` header fields. For example `res.send()` and `res.render()` default to "utf8", so we may explicitly set the charset before rendering a template:789790 res.charset = 'ISO-8859-1';791 res.render('users');792793or before responding with `res.send()`:794795 res.charset = 'ISO-8859-1';796 res.send(str);797798or with node's `res.end()`:799800 res.charset = 'ISO-8859-1';801 res.header('Content-Type', 'text/plain');802 res.end(str);803Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 804–811why, one step back804### res.contentType(type)805806Sets the _Content-Type_ response header to the given _type_.807808 var filename = 'path/to/image.png';809 res.contentType(filename);810 // Content-Type is now "image/png"811docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a
lines 812–815why, one step back812A literal _Content-Type_ works as well:813814 res.contentType('application/json');815Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73
lines 816–819why, one step back816Or simply the extension without leading `.`:817818 res.contentType('json');819Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 820–848why, one step back820### res.attachment([filename])821822Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.823824 res.attachment('path/to/my/image.png');825826### res.sendfile(path[, options[, callback]])827828Used by `res.download()` to transfer an arbitrary file. 829830 res.sendfile('path/to/my.file');831832This method accepts an optional callback which is called when833an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.834835 res.sendfile(path, function(err){836 if (err) {837 next(err);838 } else {839 console.log('transferred %s', path);840 }841 });842843Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:844845 res.sendfile(path, { bufferSize: 1024 }, function(err){846 // handle847 });848docsTj Holowaychukbefore adoption236a412
line 849why, one step back849### res.download(file[, filename[, callback[, callback2]]])Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 850–860why, one step back850851Transfer the given _file_ as an attachment with optional alternative _filename_.852853 res.download('path/to/image.png');854 res.download('path/to/image.png', 'foo.png');855856This is equivalent to:857858 res.attachment(file);859 res.sendfile(file);860docsTj Holowaychukbefore adoption236a412
line 861why, one step back861An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_. Within this callback you may still respond, as the header has not been sent.Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 862–864why, one step back862863 res.download(path, 'expenses.doc', function(err){864 // handledocsTj Holowaychukbefore adoption236a412
lines 865–872why, one step back865 });866867An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.868869 res.download(path, function(err){870 // error or finished871 }, function(err){872 // connection related errorAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 873–918why, one step back873 });874875### res.send(body|status[, headers|status[, status]])876877The _res.send()_ method is a high level response utility allowing you to pass878objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:879880 res.send(); // 204881 res.send(new Buffer('wahoo'));882 res.send({ some: 'json' });883 res.send('<p>some html</p>');884 res.send('Sorry, cant find that', 404);885 res.send('text', { 'Content-Type': 'text/plain' }, 201);886 res.send(404);887888By default the _Content-Type_ response header is set, however if explicitly889assigned through `res.send()` or previously with `res.header()` or `res.contentType()`890it will not be set again.891892Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.893894### res.redirect(url[, status])895896Redirect to the given _url_ with a default response _status_ of 302.897898 res.redirect('/', 301);899 res.redirect('/account');900 res.redirect('http://google.com');901 res.redirect('home');902 res.redirect('back');903904Express supports "redirect mapping", which by default provides _home_, and _back_.905The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes906the "home" setting and defaults to "/".907908### res.cookie(name, val[, options])909910Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.911912 // "Remember me" for 15 minutes 913 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });914915The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:916917 res.cookie('rememberme', 'yes', { maxAge: 900000 });918doc typoTj Holowaychukbefore adoption62df63d
line 919why, one step back919To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 920–926why, one step back920921 app.use(express.cookieParser());922 923 app.get('/', function(req, res){924 // use req.cookies.rememberme925 });926Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 927why, one step back927### res.clearCookie(name[, options])Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 928–978why, one step back928929Clear cookie _name_ by setting "expires" far in the past.930931 res.clearCookie('rememberme');932933### res.render(view[, options[, fn]])934935Render _view_ with the given _options_ and optional callback _fn_.936When a callback function is given a response will _not_ be made937automatically, however otherwise a response of _200_ and _text/html_ is given.938939The _options_ passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:940941 var user = { name: 'tj' };942 res.render('index', { layout: false, user: user });943944### res.partial(view[, options])945946Render _view_ partial with the given _options_. This method is always available947to the view as a local variable.948949- _object_ the object named by _as_ or derived from the view name950- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.951 * as: 'something' will add the _something_ local variable952 * as: this will use the collection value as the template context953 * as: global will merge the collection value's properties with _locals_954955- _collection_ Array of objects, the name is derived from the view name itself. 956 For example _video.html_ will have a object _video_ available to it.957958The following are equivalent, and the name of collection value when passed959to the partial will be _movie_ as derived from the name.960961 partial('theatre/movie.jade', { collection: movies });962 partial('theatre/movie.jade', movies);963 partial('movie.jade', { collection: movies });964 partial('movie.jade', movies);965 partial('movie', movies);966 // In view: movie.director967968To change the local from _movie_ to _video_ we can use the "as" option:969970 partial('movie', { collection: movies, as: 'video' });971 // In view: video.director972973Also we can make our movie the value of _this_ within our view so that instead974of _movie.director_ we could use _this.director_.975976 partial('movie', { collection: movies, as: this });977 // In view: this.director978docs for partial changesTj Holowaychukbefore adoption20b8fac
line 979why, one step back979Another alternative is to "expand" the properties of the collection item intoAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 980–1000why, one step back980pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:981982 partial('movie', { collection: movies, as: global });983 // In view: director984985This same logic applies to a single partial object usage:986987 partial('movie', { object: movie, as: this });988 // In view: this.director989990 partial('movie', { object: movie, as: global });991 // In view: director992993 partial('movie', { object: movie, as: 'video' });994 // In view: video.director995996 partial('movie', { object: movie });997 // In view: movie.director998999When a non-collection (does _not_ have _.length_) is passed as the second argument, it is assumed to be the _object_, after which the object's local variable name is derived from the view name:1000docs for partial changesTj Holowaychukbefore adoption20b8fac
lines 1001–1002why, one step back1001 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1002 partial('movie', movie)Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
line 1003why, one step back1003 // => In view: movie.directordocs for partial changesTj Holowaychukbefore adoption20b8fac
lines 1004–1014why, one step back10041005The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:10061007 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1008 partial('movie', movie)10091010For cases like this where passing a plain object is desired, simply assign it to a key, or use the `object` key which will use the filename-derived variable name. The examples below are equivalent:10111012 partial('movie', { locals: { movie: movie }})1013 partial('movie', { movie: movie })1014 partial('movie', { object: movie })Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1015–1047why, one step back10151016This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:10171018 app.get('/users', function(req, res){1019 if (req.xhr) {1020 // respond with the each user in the collection1021 // passed to the "user" view1022 res.partial('user', users);1023 } else {1024 // respond with layout, and users page1025 // which internally does partial('user', users)1026 // along with other UI1027 res.render('users', { users: users });1028 }1029 });10301031### res.local(name[, val])10321033Get or set the given local variable _name_. The locals built up for a response are applied to those given to the view rendering methods such as `res.render()`.10341035 app.all('/movie/:id', function(req, res, next){1036 Movie.get(req.params.id, function(err, movie){1037 // Assigns res.locals.movie = movie1038 res.local('movie', movie);1039 });1040 });1041 1042 app.get('/movie/:id', function(req, res){1043 // movie is already a local, however we1044 // can pass more if we wish1045 res.render('movie', { displayReviews: true });1046 });1047doc typoTj Holowaychukbefore adoptionc3e6326
line 1048why, one step back1048### res.locals(obj)Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 1049–1056why, one step back10491050 Assign several locals with the given _obj_. The following are equivalent:1051 1052 res.local('foo', bar);1053 res.local('bar', baz);10541055 res.locals({ foo: bar, bar, baz });1056Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1057–1170why, one step back1057### app.set(name[, val])10581059Apply an application level setting _name_ to _val_, or1060get the value of _name_ when _val_ is not present:10611062 app.set('views', __dirname + '/views');1063 app.set('views');1064 // => ...path...10651066Alternatively you may simply access the settings via _app.settings_:10671068 app.settings.views1069 // => ...path...10701071### app.enable(name)10721073Enable the given setting _name_:10741075 app.enable('some arbitrary setting');1076 app.set('some arbitrary setting');1077 // => true10781079 app.enabled('some arbitrary setting');1080 // => true10811082### app.enabled(name)10831084Check if setting _name_ is enabled:10851086 app.enabled('view cache');1087 // => false10881089 app.enable('view cache');1090 app.enabled('view cache');1091 // => true10921093### app.disable(name)10941095Disable the given setting _name_:10961097 app.disable('some setting');1098 app.set('some setting');1099 // => false1100 1101 app.disabled('some setting');1102 // => false11031104### app.disabled(name)11051106Check if setting _name_ is disabled:11071108 app.enable('view cache');11091110 app.disabled('view cache');1111 // => false11121113 app.disable('view cache');1114 app.disabled('view cache');1115 // => true11161117### app.configure(env|function[, function])11181119Define a callback function for the given _env_ (or all environments) with callback _function_:11201121 app.configure(function(){1122 // executed for each env1123 });11241125 app.configure('development', function(){1126 // executed for 'development' only1127 });11281129### app.redirect(name, val)11301131For use with _res.redirect()_ we can map redirects at the application level as shown below:11321133 app.redirect('google', 'http://google.com');11341135Now in a route we may call:11361137 res.redirect('google');11381139We may also map dynamic redirects:11401141 app.redirect('comments', function(req, res){1142 return '/post/' + req.params.id + '/comments';1143 });11441145So now we may do the following, and the redirect will dynamically adjust to1146the context of the request. If we called this route with _GET /post/12_ our1147redirect _Location_ would be _/post/12/comments_.11481149 app.get('/post/:id', function(req, res){1150 res.redirect('comments');1151 });11521153When mounted, _res.redirect()_ will respect the mount-point. For example if a blog app is mounted at _/blog_, the following will redirect to _/blog/posts_:11541155 res.redirect('/posts');11561157### app.error(function)11581159Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1160Note that we may set several error handlers by making several calls to this method, however the handler1161should call _next(err)_ if it does not wish to deal with the exception:11621163 app.error(function(err, req, res, next){1164 res.send(err.message, 500);1165 });11661167### app.helpers(obj)11681169Registers static view helpers.1170Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1171–1175why, one step back1171 app.helpers({1172 name: function(first, last){ return first + ', ' + last }1173 , firstName: 'tj'1174 , lastName: 'holowaychuk'1175 });Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1176–1180why, one step back11761177Our view could now utilize the _firstName_ and _lastName_ variables,1178as well as the _name()_ function exposed.11791180 <%= name(firstName, lastName) %>Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1181–1184why, one step back11811182Express also provides a few locals by default:11831184 - `settings` the app's settings objectdocs for "filename" localTj Holowaychukbefore adoptionbf06d90
line 1185why, one step back1185 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1186why, one step back1186 - `layout(path)` specify the layout from within a viewAdded 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1187–1188why, one step back11871188This method is aliased as _app.locals()_.Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1189–1206why, one step back11891190### app.dynamicHelpers(obj)11911192Registers dynamic view helpers. Dynamic view helpers1193are simply functions which accept _req_, _res_, and are1194evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1195becomes the local variable it is associated with.11961197 app.dynamicHelpers({1198 session: function(req, res){1199 return req.session;1200 }1201 });12021203All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12041205 <%= session.name %>1206docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1207–1211why, one step back1207### app.lookup12081209 The _app.lookup_ http methods returns an array of callback functions1210 associated with the given _path_.1211docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1212why, one step back1212 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1213–1215why, one step back1213 1214 app.get('/user/:id', function(){});1215 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1216why, one step back1216 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1217–1224why, one step back12171218 We can utilize this lookup functionality to check which routes1219 have been defined, which can be extremely useful for higher level1220 frameworks built on Express.12211222 app.lookup.get('/user/:id');1223 // => [Function]1224docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1225why, one step back1225 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1226–1242why, one step back1226 // => [Function]12271228 app.lookup.put('/user/:id');1229 // => [Function]12301231 app.lookup.all('/user/:id');1232 // => [Function, Function]12331234 app.lookup.all('/hey');1235 // => []12361237 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1238 without a callback, as a shortcut, for example the following are1239 equivalent:1240 1241 app.lookup.get('/user');1242 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1243why, one step back1243more docsTj Holowaychukbefore adoption6230ec5
lines 1244–1259why, one step back1244 Each function returned has the following properties:1245 1246 var fn = app.get('/user/:id/:op?')[0];12471248 fn.regexp1249 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12501251 fn.keys1252 // => ['id', 'op']12531254 fn.path1255 // => '/user/:id/:op?'12561257 fn.method1258 // => 'GET'1259docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1260–1287why, one step back1260### app.match12611262 The _app.match_ http methods return an array of callback functions1263 which match the given _url_, which may include a query string etc. This1264 is useful when you want reflect on which routes have the opportunity to1265 respond.12661267 Suppose we define the following routes:12681269 app.get('/user/:id', function(){});1270 app.put('/user/:id', function(){});1271 app.get('/user/:id/:op?', function(){});12721273 Our match against __GET__ will return two functions, since the _:op_1274 in our second route is optional.12751276 app.match.get('/user/1');1277 // => [Function, Function]12781279 This second call returns only the callback for _/user/:id/:op?_.12801281 app.match.get('/user/23/edit');1282 // => [Function]12831284 We can also use _all()_ to disregard the http method:12851286 app.match.all('/user/20');1287 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1288–1300why, one step back12881289 Each function matched has the following properties:1290 1291 var fn = app.match.get('/user/23/edit')[0];12921293 fn.keys1294 // => ['id', 'op']12951296 fn.params1297 // => { id: '23', op: 'edit' }12981299 fn.method1300 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1301why, one step back1301Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1302–1370why, one step back1302### app.mounted(fn)13031304Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13051306 var app = express.createServer(),1307 blog = express.createServer();1308 1309 blog.mounted(function(parent){1310 // parent is app1311 // "this" is blog1312 });1313 1314 app.use(blog);13151316### app.register(ext, exports)13171318Register the given template engine _exports_1319as _ext_. For example we may wish to map ".html"1320files to jade:13211322 app.register('.html', require('jade'));13231324This is also useful for libraries that may not1325match extensions correctly. For example my haml.js1326library is installed from npm as "hamljs" so instead1327of layout.hamljs, we can register the engine as ".haml":13281329 app.register('.haml', require('haml-js'));13301331For engines that do not comply with the Express1332specification, we can also wrap their api this way. Below1333we map _.md_ to render markdown files, rendering the html once1334since it will not change on subsequent calls, and support local substitution1335in the form of "{name}".13361337 app.register('.md', {1338 compile: function(str, options){1339 var html = md.toHTML(str);1340 return function(locals){1341 return html.replace(/\{([^}]+)\}/g, function(_, name){1342 return locals[name];1343 });1344 };1345 }1346 });13471348### app.listen([port[, host]])13491350Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1351connections will be accepted via _INADDR_ANY_.13521353 app.listen();1354 app.listen(3000);1355 app.listen(3000, 'n.n.n.n');13561357The _port_ argument may also be a string representing the path to a unix domain socket:13581359 app.listen('/tmp/express.sock');13601361Then try it out:13621363 $ telnet /tmp/express.sock1364 GET / HTTP/1.113651366 HTTP/1.1 200 OK1367 Content-Type: text/plain1368 Content-Length: 111369 1370 Hello World