guide.md
This file
Path
docs/guide.md
1,371 lines · 48.0 KiB · Markdown
Last changed by
added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
History of this fileTake it
The walk stopped after 200 commits: lines older than 4c274c5 point at it.
Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1–49why, one step back12### Installation34 $ npm install express56### Creating A Server78 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()_.910 var app = require('express').createServer();11 12 app.get('/', function(req, res){13 res.send('hello world');14 });15 16 app.listen(3000);1718### Creating An HTTPS Server1920 To initialize a _express.HTTPSServer_ we do the same as above, however we21 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).22 23 var app = require('express').createServer({ key: ... });2425### Configuration2627Express supports arbitrary environments, such as _production_ and _development_. Developers28can use the _configure()_ method to setup needs required by the current environment. When29_configure()_ is called without an environment name it will be run in _every_ environment 30prior to the environment specific callback.3132In the example below we only _dumpExceptions_, and respond with exception stack traces33in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.34Note the use of _app.router_, which can (optionally) be used to mount the application routes,35otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.3637 app.configure(function(){38 app.use(express.methodOverride());39 app.use(express.bodyParser());40 app.use(app.router);41 });42 43 app.configure('development', function(){44 app.use(express.static(__dirname + '/public'));45 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));46 });47 48 app.configure('production', function(){49 var oneYear = 31557600000;Docs for staticProvider() changesTj Holowaychukbefore adoption3cacf05
line 50why, one step back50 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 51–84why, one step back51 app.use(express.errorHandler());52 });5354For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5556 app.configure(function(){57 app.set('views', __dirname + '/views');58 app.set('views');59 // => "/absolute/path/to/views"60 61 app.enable('some feature');62 // same as app.set('some feature', true);63 64 app.disable('some feature');65 // same as app.set('some feature', false);66 67 app.enabled('some feature')68 // => false69 });7071To alter the environment we can set the _NODE_ENV_ environment variable, for example:7273 $ NODE_ENV=production node app.js7475This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7677### Settings7879Express supports the following settings out of the box:8081 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.82 * _views_ Root views directory defaulting to **CWD/views**83 * _view engine_ Default view engine name for views rendered without extensions84 * _view options_ An object specifying global view optionsdocs for "view cache" settingTj Holowaychukbefore adoption805b9ac
line 85why, one step back85 * _view cache_ Enable view caching (enabled in production)Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd
line 86why, one step back86 * _case sensitive routes_ Enable case-sensitive routingAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 87–169why, one step back8788### Routing8990Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.91For example we may want to render a user's account for the path _/user/12_, this92can be done by defining the route below. The values associated to the named placeholders 93are available as `req.params`.9495 app.get('/user/:id', function(req, res){96 res.send('user ' + req.params.id);97 });9899A route is simple a string which is compiled to a _RegExp_ internally. For example100when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:101102 \/user\/([^\/]+)\/?103104Regular expression literals may also be passed for complex uses. Since capture105groups 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]_.106107 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){108 res.send(req.params);109 });110111Curl requests against the previously defined route:112113 $ curl http://dev:3000/user114 [null,null]115 $ curl http://dev:3000/users116 [null,null]117 $ curl http://dev:3000/users/1118 ["1",null]119 $ curl http://dev:3000/users/1..15120 ["1","15"]121122Below are some route examples, and the associated paths that they123may consume:124125 "/user/:id"126 /user/12127128 "/users/:id?"129 /users/5130 /users131132 "/files/*"133 /files/jquery.js134 /files/javascripts/jquery.js135136 "/file/*.*"137 /files/jquery.js138 /files/javascripts/jquery.js139 140 "/user/:id/:operation?"141 /user/1142 /user/1/edit143 144 "/products.:format"145 /products.json146 /products.xml147148 "/products.:format?"149 /products.json150 /products.xml151 /products152 153 "/user/:id.:format?"154 /user/12155 /user/12.json156157For 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_:158159 var express = require('express')160 , app = express.createServer();161162 app.use(express.bodyParser());163164 app.post('/', function(req, res){165 res.send(req.body);166 });167168 app.listen(3000);169docsTj Holowaychukbefore adoption6106188
line 170why, one step back170Typically 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 res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 171–251why, one step back171172### Passing Route Control173174We may pass control to the next _matching_ route, by calling the _third_ argument,175the _next()_ function. When a match cannot be made, control is passed back to Connect,176and 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.177178 app.get('/users/:id?', function(req, res, next){179 var id = req.params.id;180 if (id) {181 // do something182 } else {183 next();184 }185 });186 187 app.get('/users', function(req, res){188 // do something else189 });190191The _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_.192193 var express = require('express')194 , app = express.createServer();195196 var users = [{ name: 'tj' }];197198 app.all('/user/:id/:op?', function(req, res, next){199 req.user = users[req.params.id];200 if (req.user) {201 next();202 } else {203 next(new Error('cannot find user ' + req.params.id));204 }205 });206207 app.get('/user/:id', function(req, res){208 res.send('viewing ' + req.user.name);209 });210211 app.get('/user/:id/edit', function(req, res){212 res.send('editing ' + req.user.name);213 });214215 app.put('/user/:id', function(req, res){216 res.send('updating ' + req.user.name);217 });218219 app.get('*', function(req, res){220 res.send('what???', 404);221 });222223 app.listen(3000); 224225### Middleware226227Middleware via [Connect](http://github.com/senchalabs/connect) can be228passed to _express.createServer()_ as you would with a regular Connect server. For example:229230 var express = require('express');231232 var app = express.createServer(233 express.logger()234 , express.bodyParser()235 );236237Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.238239 app.use(express.logger({ format: ':method :uri' }));240241Typically with connect middleware you would _require('connect')_ like so:242243 var connect = require('connect');244 app.use(connect.logger());245 app.use(connect.bodyParser());246247This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:248249 app.use(express.logger());250 app.use(express.bodyParser());251added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
lines 252–278why, one step back252Middleware 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()_.253254Many 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 below255256 app.use(express.logger(...));257 app.use(express.bodyParser(...));258 app.use(express.cookieParser(...));259 app.use(express.session(...));260 app.use(app.router);261 app.use(express.static(...));262 app.use(express.errorHandler(...));263264First 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.265266 var downloads = {};267268 app.use(app.router);269 app.use(express.static(__dirname + '/public'));270271 app.get('/*', function(req, res, next){272 var file = req.params[0];273 downloads[file] = downloads[file] || 0;274 downloads[file]++;275 next();276 });277278Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 279–349why, one step back279### Route Middleware280281Routes 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.282283Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 284285 app.get('/user/:id', function(req, res, next){286 loadUser(req.params.id, function(err, user){287 if (err) return next(err);288 res.send('Viewing user ' + user.name);289 });290 });291292To 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. 293294 function loadUser(req, res, next) {295 // You would fetch your user from the db296 var user = users[req.params.id];297 if (user) {298 req.user = user;299 next();300 } else {301 next(new Error('Failed to load user ' + req.params.id));302 }303 }304 305 app.get('/user/:id', loadUser, function(req, res){306 res.send('Viewing user ' + req.user.name);307 });308309Multiple 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.310311 function andRestrictToSelf(req, res, next) {312 req.authenticatedUser.id == req.user.id313 ? next()314 : next(new Error('Unauthorized'));315 }316 317 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){318 res.send('Editing user ' + req.user.name);319 });320321Keeping 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.322323 function andRestrictTo(role) {324 return function(req, res, next) {325 req.authenticatedUser.role == role326 ? next()327 : next(new Error('Unauthorized'));328 }329 }330 331 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){332 res.send('Deleted user ' + req.user.name);333 });334335Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.336337 var a = [middleware1, middleware2]338 , b = [middleware3, middleware4]339 , all = [a, b];340 341 app.get('/foo', a, function(){});342 app.get('/bar', a, function(){});343 344 app.get('/', a, middleware3, middleware4, function(){});345 app.get('/', a, b, function(){});346 app.get('/', all, function(){});347348For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.349docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 350–351why, one step back350There 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.351Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 352–405why, one step back352### HTTP Methods353354We 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.355356 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.357 358 <form method="post" action="/">359 <input type="text" name="user[name]" />360 <input type="text" name="user[email]" />361 <input type="submit" value="Submit" />362 </form>363364By 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:365366 app.use(express.bodyParser());367368Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.369370 app.post('/', function(req, res){371 console.log(req.body.user);372 res.redirect('back');373 });374375When 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.376377 app.use(express.bodyParser());378 app.use(express.methodOverride());379380The 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:381382 <form method="post" action="/">383 <input type="hidden" name="_method" value="put" />384 <input type="text" name="user[name]" />385 <input type="text" name="user[email]" />386 <input type="submit" value="Submit" /> 387 </form>388389 app.put('/', function(){390 console.log(req.body.user);391 res.redirect('back');392 });393394### Error Handling395396Express provides the _app.error()_ method which receives exceptions thrown within a route,397or passed to _next(err)_. Below is an example which serves different pages based on our398ad-hoc _NotFound_ exception:399400 function NotFound(msg){401 this.name = 'NotFound';402 Error.call(this, msg);403 Error.captureStackTrace(this, arguments.callee);404 }405 doc typoTj Holowaychukbefore adoptionfae1ba9
line 406why, one step back406 NotFound.prototype.__proto__ = Error.prototype;Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 407–556why, one step back407 408 app.get('/404', function(req, res){409 throw new NotFound;410 });411 412 app.get('/500', function(req, res){413 throw new Error('keyboard cat!');414 });415416We can call _app.error()_ several times as shown below.417Here we check for an instanceof _NotFound_ and show the418404 page, or we pass on to the next error handler.419420Note that these handlers can be defined anywhere, as they421will be placed below the route handlers on _listen()_. This 422allows for definition within _configure()_ blocks so we can423handle exceptions in different ways based on the environment.424425 app.error(function(err, req, res, next){426 if (err instanceof NotFound) {427 res.render('404.jade');428 } else {429 next(err);430 }431 });432433Here we assume all errors as 500 for the simplicity of434this 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.435436 app.error(function(err, req, res){437 res.render('500.jade', {438 error: err439 });440 });441442Our apps could also utilize the Connect _errorHandler_ middleware443to report on exceptions. For example if we wish to output exceptions 444in "development" mode to _stderr_ we can use:445446 app.use(express.errorHandler({ dumpExceptions: true }));447448Also during development we may want fancy html pages to show exceptions449that are passed or thrown, so we can set _showStack_ to true:450451 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));452453The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_454is present, which is useful for developing apps that rely heavily on client-side JavaScript.455456### Route Param Pre-conditions457458Route 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:459460 app.get('/user/:userId', function(req, res, next){461 User.get(req.params.userId, function(err, user){462 if (err) return next(err);463 res.send('user ' + user.name);464 });465 }); 466467With 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.468469 app.param('userId', function(req, res, next, id){470 User.get(id, function(err, user){471 if (err) return next(err);472 if (!user) return next(new Error('failed to find user'));473 req.user = user;474 next();475 });476 });477478Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:479480 app.get('/user/:userId', function(req, res){481 res.send('user ' + req.user.name);482 });483484For 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)_.485486 app.param('number', function(n){ return parseInt(n, 10); });487488We 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:489490 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });491492### View Rendering493494View filenames take the form "<name>.<engine>", where <engine> is the name495of the module that will be required. For example the view _layout.ejs_ will496tell 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 behaviour497_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.498499Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,500and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 501the _body_ local variable in _layout.jade_.502503 app.get('/', function(req, res){504 res.render('index.jade', { title: 'My Site' });505 });506507The new _view engine_ setting allows us to specify our default template engine,508so for example when using jade we could set:509510 app.set('view engine', 'jade');511512Allowing us to render with:513514 res.render('index');515516vs:517518 res.render('index.jade');519520When _view engine_ is set, extensions are entirely optional, however we can still521mix and match template engines:522523 res.render('another-page.ejs');524525Express 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:526527 app.set('view options', {528 layout: false529 });530531Which can then be overridden within the _res.render()_ call if need be:532533 res.render('myview.ejs', { layout: true });534535When 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:536537 res.render('page', { layout: 'mylayout' });538539Otherwise we must specify the extension:540541 res.render('page', { layout: 'mylayout.jade' });542543These paths may also be absolute:544545 res.render('page', { layout: __dirname + '/../../mylayout.jade' });546547A good example of this is specifying custom _ejs_ opening and closing tags:548549 app.set('view options', {550 open: '{{',551 close: '}}'552 });553554### View Partials555556The 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 557why, one step back557in a view to display comments, we could use partial collection:Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 558–560why, one step back558559 partial('comment', { collection: comments });560docs for partial changesTj Holowaychukbefore adoption20b8fac
line 561why, one step back561If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 562–564why, one step back562563 partial('comment', comments);564docs for partial changesTj Holowaychukbefore adoption20b8fac
line 565why, one step back565When using the partial collection support a few "magic" locals are providedAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 566–590why, one step back566for free:567568 * _firstInCollection_ true if this is the first object569 * _indexInCollection_ index of the object in the collection570 * _lastInCollection_ true if this is the last object571 * _collectionLength_ length of the collection572573Local 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.574575For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).576577__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.578579### View Lookup580581View 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_.582583The 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_.584585When 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')_.586587### Template Engines588589Below are a few template engines commonly used with Express:590Add haml back in docsTj Holowaychukbefore adoptione85752c
line 591why, one step back591 * [Haml](http://github.com/visionmedia/haml.js) haml implementationAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 592–786why, one step back592 * [Jade](http://jade-lang.com) haml.js successor593 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript594 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating595 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node596597### Session Support598599Sessions 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_.600601 app.use(express.cookieParser());602 app.use(express.session({ secret: "keyboard cat" }));603604By 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:605606 var RedisStore = require('connect-redis');607 app.use(express.cookieParser());608 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));609610Now 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:611612 var RedisStore = require('connect-redis');613 app.use(express.bodyParser());614 app.use(express.cookieParser());615 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));616617 app.post('/add-to-cart', function(req, res){618 // Perhaps we posted several items with a form619 // (use the bodyParser() middleware for this)620 var items = req.body.items;621 req.session.items = items;622 res.redirect('back');623 });624625 app.get('/add-to-cart', function(req, res){626 // When redirected back to GET /add-to-cart627 // we could check req.session.items && req.session.items.length628 // to print out a message629 if (req.session.items && req.session.items.length) {630 req.flash('info', 'You have %s items in your cart', req.session.items.length);631 }632 res.render('shopping-cart');633 });634635The _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.636637### Migration Guide638639 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.640641### req.header(key[, defaultValue])642643Get the case-insensitive request header _key_, with optional _defaultValue_:644645 req.header('Host');646 req.header('host');647 req.header('Accept', '*/*');648649The _Referrer_ and _Referer_ header fields are special-cased, either will work:650651 // sent Referrer: http://google.com652653 req.header('Referer');654 // => "http://google.com"655656 req.header('Referrer');657 // => "http://google.com"658659### req.accepts(type)660661Check if the _Accept_ header is present, and includes the given _type_.662663When the _Accept_ header is not present _true_ is returned. Otherwise664the given _type_ is matched by an exact match, and then subtypes. You665may pass the subtype such as "html" which is then converted internally666to "text/html" using the mime lookup table.667668 // Accept: text/html669 req.accepts('html');670 // => true671672 // Accept: text/*; application/json673 req.accepts('html');674 req.accepts('text/html');675 req.accepts('text/plain');676 req.accepts('application/json');677 // => true678679 req.accepts('image/png');680 req.accepts('png');681 // => false682683### req.is(type)684685Check if the incoming request contains the _Content-Type_686header field, and it contains the give mime _type_.687 688 // With Content-Type: text/html; charset=utf-8689 req.is('html');690 req.is('text/html');691 // => true692 693 // When Content-Type is application/json694 req.is('json');695 req.is('application/json');696 // => true697 698 req.is('html');699 // => false700 701Ad-hoc callbacks can also be registered with Express, to perform702assertions again the request, for example if we need an expressive703way to check if our incoming request is an image, we can register _"an image"_704callback:705 706 app.is('an image', function(req){707 return 0 == req.headers['content-type'].indexOf('image');708 });709 710Now within our route callbacks, we can use to to assert content types711such as _"image/jpeg"_, _"image/png"_, etc.712 713 app.post('/image/upload', function(req, res, next){714 if (req.is('an image')) {715 // do something716 } else {717 next();718 }719 });720721Keep in mind this method is _not_ limited to checking _Content-Type_, you722can perform any request assertion you wish.723724Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:725726 req.is('image/*');727728We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.729730 req.is('*/json');731732### req.param(name[, default])733734Return the value of param _name_ when present or _default_.735736 - Checks route params (_req.params_), ex: /user/:id737 - Checks query string params (_req.query_), ex: ?id=12738 - Checks urlencoded body params (_req.body_), ex: id=12739740To utilize urlencoded request bodies, _req.body_741should be an object. This can be done by using742the _express.bodyParser middleware.743744### req.flash(type[, msg])745746Queue flash _msg_ of the given _type_.747748 req.flash('info', 'email sent');749 req.flash('error', 'email delivery failed');750 req.flash('info', 'email re-sent');751 // => 2752753 req.flash('info');754 // => ['email sent', 'email re-sent']755756 req.flash('info');757 // => []758759 req.flash();760 // => { error: ['email delivery failed'], info: [] }761762Flash notification message may also utilize formatters, by default only the %s string formatter is available:763764 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);765766### req.isXMLHttpRequest767768Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header769to see if it was issued by an _XMLHttpRequest_:770771 req.xhr772 req.isXMLHttpRequest773774### res.header(key[, val])775776Get or set the response header _key_.777778 res.header('Content-Length');779 // => undefined780781 res.header('Content-Length', 123);782 // => 123783 784 res.header('Content-Length');785 // => 123786docs for charsetTj Holowaychukbefore adoptiond12452f
lines 787–804why, one step back787### res.charset788789Sets 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:790791 res.charset = 'ISO-8859-1';792 res.render('users');793794or before responding with `res.send()`:795796 res.charset = 'ISO-8859-1';797 res.send(str);798799or with node's `res.end()`:800801 res.charset = 'ISO-8859-1';802 res.header('Content-Type', 'text/plain');803 res.end(str);804Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 805–812why, one step back805### res.contentType(type)806807Sets the _Content-Type_ response header to the given _type_.808809 var filename = 'path/to/image.png';810 res.contentType(filename);811 // Content-Type is now "image/png"812docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a
lines 813–816why, one step back813A literal _Content-Type_ works as well:814815 res.contentType('application/json');816Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73
lines 817–820why, one step back817Or simply the extension without leading `.`:818819 res.contentType('json');820Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 821–849why, one step back821### res.attachment([filename])822823Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.824825 res.attachment('path/to/my/image.png');826827### res.sendfile(path[, options[, callback]])828829Used by `res.download()` to transfer an arbitrary file. 830831 res.sendfile('path/to/my.file');832833This method accepts an optional callback which is called when834an 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.835836 res.sendfile(path, function(err){837 if (err) {838 next(err);839 } else {840 console.log('transferred %s', path);841 }842 });843844Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:845846 res.sendfile(path, { bufferSize: 1024 }, function(err){847 // handle848 });849docsTj Holowaychukbefore adoption236a412
line 850why, one step back850### res.download(file[, filename[, callback[, callback2]]])Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 851–861why, one step back851852Transfer the given _file_ as an attachment with optional alternative _filename_.853854 res.download('path/to/image.png');855 res.download('path/to/image.png', 'foo.png');856857This is equivalent to:858859 res.attachment(file);860 res.sendfile(file);861docsTj Holowaychukbefore adoption236a412
line 862why, one step back862An 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 res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 863–865why, one step back863864 res.download(path, 'expenses.doc', function(err){865 // handledocsTj Holowaychukbefore adoption236a412
lines 866–873why, one step back866 });867868An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.869870 res.download(path, function(err){871 // error or finished872 }, function(err){873 // connection related errorAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 874–915why, one step back874 });875876### res.send(body|status[, headers|status[, status]])877878The _res.send()_ method is a high level response utility allowing you to pass879objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:880881 res.send(); // 204882 res.send(new Buffer('wahoo'));883 res.send({ some: 'json' });884 res.send('<p>some html</p>');885 res.send('Sorry, cant find that', 404);886 res.send('text', { 'Content-Type': 'text/plain' }, 201);887 res.send(404);888889By default the _Content-Type_ response header is set, however if explicitly890assigned through `res.send()` or previously with `res.header()` or `res.contentType()`891it will not be set again.892893Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.894895### res.redirect(url[, status])896897Redirect to the given _url_ with a default response _status_ of 302.898899 res.redirect('/', 301);900 res.redirect('/account');901 res.redirect('http://google.com');902 res.redirect('home');903 res.redirect('back');904905Express supports "redirect mapping", which by default provides _home_, and _back_.906The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes907the "home" setting and defaults to "/".908909### res.cookie(name, val[, options])910911Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.912913 // "Remember me" for 15 minutes 914 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });915docs for res.cookie()Tj Holowaychukbefore adoption00e1dbf
lines 916–919why, one step back916The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:917918 res.cookie('rememberme', 'yes', { maxAge: 900000 });919doc typoTj Holowaychukbefore adoption62df63d
line 920why, one step back920To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 921–927why, one step back921922 app.use(express.cookieParser());923 924 app.get('/', function(req, res){925 // use req.cookies.rememberme926 });927Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 928why, one step back928### res.clearCookie(name[, options])Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 929–979why, one step back929930Clear cookie _name_ by setting "expires" far in the past.931932 res.clearCookie('rememberme');933934### res.render(view[, options[, fn]])935936Render _view_ with the given _options_ and optional callback _fn_.937When a callback function is given a response will _not_ be made938automatically, however otherwise a response of _200_ and _text/html_ is given.939940The _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:941942 var user = { name: 'tj' };943 res.render('index', { layout: false, user: user });944945### res.partial(view[, options])946947Render _view_ partial with the given _options_. This method is always available948to the view as a local variable.949950- _object_ the object named by _as_ or derived from the view name951- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.952 * as: 'something' will add the _something_ local variable953 * as: this will use the collection value as the template context954 * as: global will merge the collection value's properties with _locals_955956- _collection_ Array of objects, the name is derived from the view name itself. 957 For example _video.html_ will have a object _video_ available to it.958959The following are equivalent, and the name of collection value when passed960to the partial will be _movie_ as derived from the name.961962 partial('theatre/movie.jade', { collection: movies });963 partial('theatre/movie.jade', movies);964 partial('movie.jade', { collection: movies });965 partial('movie.jade', movies);966 partial('movie', movies);967 // In view: movie.director968969To change the local from _movie_ to _video_ we can use the "as" option:970971 partial('movie', { collection: movies, as: 'video' });972 // In view: video.director973974Also we can make our movie the value of _this_ within our view so that instead975of _movie.director_ we could use _this.director_.976977 partial('movie', { collection: movies, as: this });978 // In view: this.director979docs for partial changesTj Holowaychukbefore adoption20b8fac
line 980why, one step back980Another alternative is to "expand" the properties of the collection item intoAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 981–1001why, one step back981pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:982983 partial('movie', { collection: movies, as: global });984 // In view: director985986This same logic applies to a single partial object usage:987988 partial('movie', { object: movie, as: this });989 // In view: this.director990991 partial('movie', { object: movie, as: global });992 // In view: director993994 partial('movie', { object: movie, as: 'video' });995 // In view: video.director996997 partial('movie', { object: movie });998 // In view: movie.director9991000When 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:1001docs for partial changesTj Holowaychukbefore adoption20b8fac
lines 1002–1003why, one step back1002 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1003 partial('movie', movie)Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
line 1004why, one step back1004 // => In view: movie.directordocs for partial changesTj Holowaychukbefore adoption20b8fac
lines 1005–1015why, one step back10051006The 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:10071008 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1009 partial('movie', movie)10101011For 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:10121013 partial('movie', { locals: { movie: movie }})1014 partial('movie', { movie: movie })1015 partial('movie', { object: movie })Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1016–1048why, one step back10161017This 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:10181019 app.get('/users', function(req, res){1020 if (req.xhr) {1021 // respond with the each user in the collection1022 // passed to the "user" view1023 res.partial('user', users);1024 } else {1025 // respond with layout, and users page1026 // which internally does partial('user', users)1027 // along with other UI1028 res.render('users', { users: users });1029 }1030 });10311032### res.local(name[, val])10331034Get 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()`.10351036 app.all('/movie/:id', function(req, res, next){1037 Movie.get(req.params.id, function(err, movie){1038 // Assigns res.locals.movie = movie1039 res.local('movie', movie);1040 });1041 });1042 1043 app.get('/movie/:id', function(req, res){1044 // movie is already a local, however we1045 // can pass more if we wish1046 res.render('movie', { displayReviews: true });1047 });1048doc typoTj Holowaychukbefore adoptionc3e6326
line 1049why, one step back1049### res.locals(obj)Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 1050–1057why, one step back10501051 Assign several locals with the given _obj_. The following are equivalent:1052 1053 res.local('foo', bar);1054 res.local('bar', baz);10551056 res.locals({ foo: bar, bar, baz });1057Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1058–1171why, one step back1058### app.set(name[, val])10591060Apply an application level setting _name_ to _val_, or1061get the value of _name_ when _val_ is not present:10621063 app.set('views', __dirname + '/views');1064 app.set('views');1065 // => ...path...10661067Alternatively you may simply access the settings via _app.settings_:10681069 app.settings.views1070 // => ...path...10711072### app.enable(name)10731074Enable the given setting _name_:10751076 app.enable('some arbitrary setting');1077 app.set('some arbitrary setting');1078 // => true10791080 app.enabled('some arbitrary setting');1081 // => true10821083### app.enabled(name)10841085Check if setting _name_ is enabled:10861087 app.enabled('view cache');1088 // => false10891090 app.enable('view cache');1091 app.enabled('view cache');1092 // => true10931094### app.disable(name)10951096Disable the given setting _name_:10971098 app.disable('some setting');1099 app.set('some setting');1100 // => false1101 1102 app.disabled('some setting');1103 // => false11041105### app.disabled(name)11061107Check if setting _name_ is disabled:11081109 app.enable('view cache');11101111 app.disabled('view cache');1112 // => false11131114 app.disable('view cache');1115 app.disabled('view cache');1116 // => true11171118### app.configure(env|function[, function])11191120Define a callback function for the given _env_ (or all environments) with callback _function_:11211122 app.configure(function(){1123 // executed for each env1124 });11251126 app.configure('development', function(){1127 // executed for 'development' only1128 });11291130### app.redirect(name, val)11311132For use with _res.redirect()_ we can map redirects at the application level as shown below:11331134 app.redirect('google', 'http://google.com');11351136Now in a route we may call:11371138 res.redirect('google');11391140We may also map dynamic redirects:11411142 app.redirect('comments', function(req, res){1143 return '/post/' + req.params.id + '/comments';1144 });11451146So now we may do the following, and the redirect will dynamically adjust to1147the context of the request. If we called this route with _GET /post/12_ our1148redirect _Location_ would be _/post/12/comments_.11491150 app.get('/post/:id', function(req, res){1151 res.redirect('comments');1152 });11531154When 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_:11551156 res.redirect('/posts');11571158### app.error(function)11591160Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1161Note that we may set several error handlers by making several calls to this method, however the handler1162should call _next(err)_ if it does not wish to deal with the exception:11631164 app.error(function(err, req, res, next){1165 res.send(err.message, 500);1166 });11671168### app.helpers(obj)11691170Registers static view helpers.1171Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1172–1176why, one step back1172 app.helpers({1173 name: function(first, last){ return first + ', ' + last }1174 , firstName: 'tj'1175 , lastName: 'holowaychuk'1176 });Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1177–1181why, one step back11771178Our view could now utilize the _firstName_ and _lastName_ variables,1179as well as the _name()_ function exposed.11801181 <%= name(firstName, lastName) %>Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1182–1185why, one step back11821183Express also provides a few locals by default:11841185 - `settings` the app's settings objectdocs for "filename" localTj Holowaychukbefore adoptionbf06d90
line 1186why, one step back1186 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1187why, one step back1187 - `layout(path)` specify the layout from within a viewAdded 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1188–1189why, one step back11881189This method is aliased as _app.locals()_.Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1190–1207why, one step back11901191### app.dynamicHelpers(obj)11921193Registers dynamic view helpers. Dynamic view helpers1194are simply functions which accept _req_, _res_, and are1195evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1196becomes the local variable it is associated with.11971198 app.dynamicHelpers({1199 session: function(req, res){1200 return req.session;1201 }1202 });12031204All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12051206 <%= session.name %>1207docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1208–1212why, one step back1208### app.lookup12091210 The _app.lookup_ http methods returns an array of callback functions1211 associated with the given _path_.1212docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1213why, one step back1213 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1214–1216why, one step back1214 1215 app.get('/user/:id', function(){});1216 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1217why, one step back1217 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1218–1225why, one step back12181219 We can utilize this lookup functionality to check which routes1220 have been defined, which can be extremely useful for higher level1221 frameworks built on Express.12221223 app.lookup.get('/user/:id');1224 // => [Function]1225docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1226why, one step back1226 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1227–1243why, one step back1227 // => [Function]12281229 app.lookup.put('/user/:id');1230 // => [Function]12311232 app.lookup.all('/user/:id');1233 // => [Function, Function]12341235 app.lookup.all('/hey');1236 // => []12371238 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1239 without a callback, as a shortcut, for example the following are1240 equivalent:1241 1242 app.lookup.get('/user');1243 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1244why, one step back1244more docsTj Holowaychukbefore adoption6230ec5
lines 1245–1260why, one step back1245 Each function returned has the following properties:1246 1247 var fn = app.get('/user/:id/:op?')[0];12481249 fn.regexp1250 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12511252 fn.keys1253 // => ['id', 'op']12541255 fn.path1256 // => '/user/:id/:op?'12571258 fn.method1259 // => 'GET'1260docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1261–1288why, one step back1261### app.match12621263 The _app.match_ http methods return an array of callback functions1264 which match the given _url_, which may include a query string etc. This1265 is useful when you want reflect on which routes have the opportunity to1266 respond.12671268 Suppose we define the following routes:12691270 app.get('/user/:id', function(){});1271 app.put('/user/:id', function(){});1272 app.get('/user/:id/:op?', function(){});12731274 Our match against __GET__ will return two functions, since the _:op_1275 in our second route is optional.12761277 app.match.get('/user/1');1278 // => [Function, Function]12791280 This second call returns only the callback for _/user/:id/:op?_.12811282 app.match.get('/user/23/edit');1283 // => [Function]12841285 We can also use _all()_ to disregard the http method:12861287 app.match.all('/user/20');1288 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1289–1301why, one step back12891290 Each function matched has the following properties:1291 1292 var fn = app.match.get('/user/23/edit')[0];12931294 fn.keys1295 // => ['id', 'op']12961297 fn.params1298 // => { id: '23', op: 'edit' }12991300 fn.method1301 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1302why, one step back1302Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1303–1371why, one step back1303### app.mounted(fn)13041305Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13061307 var app = express.createServer(),1308 blog = express.createServer();1309 1310 blog.mounted(function(parent){1311 // parent is app1312 // "this" is blog1313 });1314 1315 app.use(blog);13161317### app.register(ext, exports)13181319Register the given template engine _exports_1320as _ext_. For example we may wish to map ".html"1321files to jade:13221323 app.register('.html', require('jade'));13241325This is also useful for libraries that may not1326match extensions correctly. For example my haml.js1327library is installed from npm as "hamljs" so instead1328of layout.hamljs, we can register the engine as ".haml":13291330 app.register('.haml', require('haml-js'));13311332For engines that do not comply with the Express1333specification, we can also wrap their api this way. Below1334we map _.md_ to render markdown files, rendering the html once1335since it will not change on subsequent calls, and support local substitution1336in the form of "{name}".13371338 app.register('.md', {1339 compile: function(str, options){1340 var html = md.toHTML(str);1341 return function(locals){1342 return html.replace(/\{([^}]+)\}/g, function(_, name){1343 return locals[name];1344 });1345 };1346 }1347 });13481349### app.listen([port[, host]])13501351Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1352connections will be accepted via _INADDR_ANY_.13531354 app.listen();1355 app.listen(3000);1356 app.listen(3000, 'n.n.n.n');13571358The _port_ argument may also be a string representing the path to a unix domain socket:13591360 app.listen('/tmp/express.sock');13611362Then try it out:13631364 $ telnet /tmp/express.sock1365 GET / HTTP/1.113661367 HTTP/1.1 200 OK1368 Content-Type: text/plain1369 Content-Length: 111370 1371 Hello World