forked from expressjs/expressjs.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.html
875 lines (819 loc) · 52.7 KB
/
api.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
<!DOCTYPE html><html><head><title>Express - api reference</title><link rel="stylesheet" href="style.css"><link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&subset=latin,latin-ext"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script><script src="app.js"></script><script src="retina.js"></script></head><body class="inner"><div class="bar"></div><section id="content"><header><section id="logo"><a href="./" class="express">express<em>3.0.0</em></a><span class="description">web application framework for<a href="http://nodejs.org"> node</a></span></section><nav class="clearfix"><a href="./" class="">Home</a><a href="./api.html" class="active">API Reference</a><a href="./guide.html" class="">Guide</a><a href="./applications.html" class="">Applications</a><a href="./community.html" class="">Community</a><a href="./faq.html" class="">FAQ</a></nav></header><ul id="menu"><li id="app-api"> <a href="#express">Application</a><ul id="app-menu"><li><a href="#express">express()</a></li><li><a href="#app.set">app.set()</a></li><li><a href="#app.get">app.get()</a></li><li><a href="#app.enable">app.enable()</a></li><li><a href="#app.disable">app.disable()</a></li><li><a href="#app.enabled">app.enabled()</a></li><li><a href="#app.disabled">app.disabled()</a></li><li><a href="#app.configure">app.configure()</a></li><li><a href="#app.use">app.use()</a></li><li><a href="#app-settings">application settings</a></li><li><a href="#app.engine">app.engine()</a></li><li><a href="#app.param">app.param()</a></li><li><a href="#app.VERB">application routing</a></li><li><a href="#app.all">app.all()</a></li><li><a href="#app.locals">app.locals</a></li><li><a href="#app.render">app.render()</a></li><li><a href="#app.routes">app.routes</a></li><li><a href="#app.listen">app.listen()</a></li></ul></li><li id="req-api"> <a href="#req.params">Request</a><ul id="req-menu"><li><a href="#req.params">req.params</a></li><li><a href="#req.query">req.query</a></li><li><a href="#req.body">req.body</a></li><li><a href="#req.files">req.files</a></li><li><a href="#req.param">req.param()</a></li><li><a href="#req.route">req.route</a></li><li><a href="#req.cookies">req.cookies</a></li><li><a href="#req.signedCookies">req.signedCookies</a></li><li><a href="#req.get">req.get()</a></li><li><a href="#req.accepts">req.accepts()</a></li><li><a href="#req.accepted">req.accepted</a></li><li><a href="#req.is">req.is()</a></li><li><a href="#req.ip">req.ip</a></li><li><a href="#req.ips">req.ips</a></li><li><a href="#req.path">req.path</a></li><li><a href="#req.host">req.host</a></li><li><a href="#req.fresh">req.fresh</a></li><li><a href="#req.stale">req.stale</a></li><li><a href="#req.xhr">req.xhr</a></li><li><a href="#req.protocol">req.protocol</a></li><li><a href="#req.secure">req.secure</a></li><li><a href="#req.subdomains">req.subdomains</a></li><li><a href="#req.originalUrl">req.originalUrl</a></li><li><a href="#req.acceptedLanguages">req.acceptedLanguages</a></li><li><a href="#req.acceptedCharsets">req.acceptedCharsets</a></li><li><a href="#req.acceptsCharset">req.acceptsCharset()</a></li><li><a href="#req.acceptsLanguage">req.acceptsLanguage()</a></li></ul></li><li id="res-api"> <a href="#res.status">Response</a><ul id="res-menu"><li><a href="#res.status">res.status()</a></li><li><a href="#res.set">res.set()</a></li><li><a href="#res.get">res.get()</a></li><li><a href="#res.cookie">res.cookie()</a></li><li><a href="#res.clearCookie">res.clearCookie()</a></li><li><a href="#res.redirect">res.redirect()</a></li><li><a href="#res.location">res.location()</a></li><li><a href="#res.charset">res.charset</a></li><li><a href="#res.send">res.send()</a></li><li><a href="#res.json">res.json()</a></li><li><a href="#res.jsonp">res.jsonp()</a></li><li><a href="#res.type">res.type()</a></li><li><a href="#res.format">res.format()</a></li><li><a href="#res.attachment">res.attachment()</a></li><li><a href="#res.sendfile">res.sendfile()</a></li><li><a href="#res.download">res.download()</a></li><li><a href="#res.links">res.links()</a></li><li><a href="#res.locals">res.locals</a></li><li><a href="#res.render">res.render()</a></li></ul></li><li id="middleware-api"><a href="#middleware">Middleware</a><ul id="middleware-menu"><li><a href="#basicAuth">basicAuth()</a></li><li><a href="#bodyParser">bodyParser()</a></li><li><a href="#compress">compress()</a></li><li><a href="#cookieParser">cookieParser()</a></li><li><a href="#cookieSession">cookieSession()</a></li><li><a href="#csrf">csrf()</a></li><li><a href="#directory">directory()</a></li></ul></li></ul><div id="right"><section><h3 id="express">express()</h3><p>Create an express application.
</p><pre class="js"><code>var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);</code></pre></section><h2>Application</h2><a name="application"></a><section><h3 id="app.set">app.set(name, value)</h3><p>Assigns setting <code>name</code> to <code>value</code>.
</p><pre class="js"><code>app.set('title', 'My Site');
app.get('title');
// => "My Site"</code></pre></section><section><h3 id="app.get">app.get(name)</h3><p>Get setting <code>name</code> value.
</p><pre class="js"><code>app.get('title');
// => undefined
app.set('title', 'My Site');
app.get('title');
// => "My Site"</code></pre></section><section><h3 id="app.enable">app.enable(name)</h3><p>Set setting <code>name</code> to <code>true</code>.
</p><pre class="js"><code>app.enable('trust proxy');
app.get('trust proxy');
// => true</code></pre></section><section><h3 id="app.disable">app.disable(name)</h3><p>Set setting <code>name</code> to <code>false</code>.
</p><pre class="js"><code>app.disable('trust proxy');
app.get('trust proxy');
// => false</code></pre></section><section><h3 id="app.enabled">app.enabled(name)</h3><p>Check if setting <code>name</code> is enabled.
</p><pre class="js"><code>app.enabled('trust proxy');
// => false
app.enable('trust proxy');
app.enabled('trust proxy');
// => true</code></pre></section><section><h3 id="app.disabled">app.disabled(name)</h3><p>Check if setting <code>name</code> is disabled.
</p><pre class="js"><code>app.disabled('trust proxy');
// => true
app.enable('trust proxy');
app.disabled('trust proxy');
// => false</code></pre></section><section><h3 id="app.configure">app.configure([env], callback)</h3><p>Conditionally invoke <code>callback</code> when <code>env</code> matches <code>app.get('env')</code>,
aka <code>process.env.NODE_ENV</code>. This method remains for legacy reason, and is effectively
an <code>if</code> statement as illustrated in the following snippets. These functions are <em>not</em>
required in order to use <code>app.set()</code> and other configuration methods.
</p><pre class="js"><code>// all environments
app.configure(function(){
app.set('title', 'My Application');
})
// development only
app.configure('development', function(){
app.set('db uri', 'localhost/dev');
})
// production only
app.configure('production', function(){
app.set('db uri', 'n.n.n.n/prod');
})
</code></pre><Is>effectively sugar for:</Is><pre class="js"><code>// all environments
app.set('title', 'My Application');
// development only
if ('development' == app.get('env')) {
app.set('db uri', 'localhost/dev');
}
// production only
if ('production' == app.get('env')) {
app.set('db uri', 'n.n.n.n/prod');
}</code></pre></section><section><h3 id="app.use">app.use([path], function)</h3><p>Use the given middleware <code>function</code>, with optional mount <code>path</code>,
defaulting to "/".
</p><pre class="js"><code>var express = require('express');
var app = express();
// simple logger
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
});
// respond
app.use(function(req, res, next){
res.send('Hello World');
});
app.listen(3000);
</code></pre><p>The "mount" path is stripped and is <strong>not</strong> visible
to the middleware <code>function</code>. The main effect of this feature is that
mounted middleware may operate without code changes regardless of its "prefix"
pathname.
</p><p>Here's a concrete example, take the typical use-case of serving files in ./public
using the <code>express.static()</code> middleware:
</p><pre class="js"><code>// GET /javascripts/jquery.js
// GET /style.css
// GET /favicon.ico
app.use(express.static(__dirname + '/public'));
</code></pre><p>Say for example you wanted to prefix all static files with "/static", you could
use the "mounting" feature to support this. Mounted middleware functions are <strong>not</strong>
invoked unless the <code>req.url</code> contains this prefix, at which point
it is stripped when the function is invoked. This affects this function only,
subsequent middleware will see <code>req.url</code> with "/static" included
unless they are mounted as well.
</p><pre class="js"><code>// GET /static/javascripts/jquery.js
// GET /static/style.css
// GET /static/favicon.ico
app.use('/static', express.static(__dirname + '/public'));
</code></pre><p>The order of which middleware are "defined" using <code>app.use()</code> is
very important, they are invoked sequentially, thus this defines middleware
precedence. For example usually <code>express.logger()</code> is the very
first middleware you would use, logging every request:
</p><pre class="js"><code>app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.use(function(req, res){
res.send('Hello');
});
</code></pre><p>Now suppose you wanted to ignore logging requests for static files, but to
continue logging routes and middleware defined after <code>logger()</code>,
you would simply move <code>static()</code> above:
</p><pre class="js"><code>app.use(express.static(__dirname + '/public'));
app.use(express.logger());
app.use(function(req, res){
res.send('Hello');
});
</code></pre><p>Another concrete example would be serving files from multiple directories,
giving precedence to "./public" over the others:
</p><pre class="js"><code>app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));</code></pre></section><section><h3 id="app-settings">settings</h3><p>The following settings are provided to alter how Express will behave:
</p><ul><li><code>env </code>Environment mode, defaults to <code>process.env.NODE_ENV</code> or "development"</li><li><code>trust proxy </code>Enables reverse proxy support, disabled by default</li><li><code>jsonp callback name </code>Changes the default callback name of <code>?callback=</code></li><li><code>json replacer </code>JSON replacer callback, null by default</li><li><code>json spaces </code>JSON response spaces for formatting, defaults to <code>2</code> in development, <code>0</code> in production</li><li><code>case sensitive routing </code>Enable case sensitivity, disabled by default, treating "/Foo" and "/foo" as the same</li><li><code>strict routing </code>Enable strict routing, by default "/foo" and "/foo/" are treated the same by the router </li><li><code>view cache </code>Enables view template compilation caching, enabled in production by default</li><li><code>view engine </code>The default engine extension to use when omitted</li><li><code>views </code>The view directory path, defaulting to "process.cwd() + '/views'"</li></ul></section><section><h3 id="app.engine">app.engine(ext, callback)</h3><p>Register the given template engine <code>callback</code> as <code>ext</code>
By default will <code>require()</code> the engine based on the
file extension. For example if you try to render
a "foo.jade" file Express will invoke the following internally,
and cache the <code>require()</code> on subsequent calls to increase
performance.
</p><pre class="js"><code>app.engine('jade', require('jade').__express);
</code></pre><p>For engines that do not provide <code>.__express</code> out of the box -
or if you wish to "map" a different extension to the template engine
you may use this method. For example mapping the EJS template engine to
".html" files:
</p><pre class="js"><code>app.engine('html', require('ejs').renderFile);
</code></pre><p>In this case EJS provides a <code>.renderFile()</code> method with
the same signature that Express expects: <code>(path, options, callback)</code>,
though note that it aliases this method as <code>ejs.__express</code> internally
so if you're using ".ejs" extensions you dont need to do anything.
</p><p>Some template engines do not follow this convention, the
<a href="https://github.com/visionmedia/consolidate.js">consolidate.js</a>
library was created to map all of node's popular template
engines to follow this convention, thus allowing them to
work seemlessly within Express.
</p><pre class="js"><code>var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);</code></pre></section><section><h3 id="app.param">app.param([name], callback)</h3><p>Map logic to route parameters. For example when <code>:user</code>
is present in a route path you may map user loading logic to automatically
provide <code>req.user</code> to the route, or perform validations
on the parameter input.
</p><p>The following snippet illustrates how the <code>callback</code>
is much like middleware, thus supporting async operations, however
providing the additional value of the parameter, here named as <code>id</code>.
An attempt to load the user is then performed, assigning <code>req.user</code>,
otherwise passing an error to <code>next(err)</code>.
</p><pre class="js"><code>app.param('user', function(req, res, next, id){
User.find(id, function(err, user){
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
</code></pre><p>Alternatively you may pass only a <code>callback</code>, in which
case you have the opportunity to alter the <code>app.param()</code> API.
For example the <a href="http://github.com/visionmedia/express-params">express-params</a>
defines the following callback which allows you to restrict parameters to a given
regular expression.
</p><p>This example is a bit more advanced, checking if the second argument is a regular
expression, returning the callback which acts much like the "user" param example.
</p><pre class="js"><code>app.param(function(name, fn){
if (fn instanceof RegExp) {
return function(req, res, next, val){
var captures;
if (captures = fn.exec(String(val))) {
req.params[name] = captures;
next();
} else {
next('route');
}
}
}
});
</code></pre><p>The method could now be used to effectively validate parameters, or also
parse them to provide capture groups:
</p><pre class="js"><code>app.param('id', /^\d+$/);
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
app.param('range', /^(\w+)\.\.(\w+)?$/);
app.get('/range/:range', function(req, res){
var range = req.params.range;
res.send('from ' + range[1] + ' to ' + range[2]);
});</code></pre></section><section><h3 id="app.VERB">app.VERB(path, [callback...], callback)</h3><p>The <code>app.VERB()</code> methods provide the routing functionality
in Express, where <strong>VERB</strong> is one of the HTTP verbs, such
as <code>app.post()</code>. Multiple callbacks may be given, all are treated
equally, and behave just like middleware, with the one exception that
these callbacks may invoke <code>next('route')</code> to bypass the
remaining route callback(s). This mechanism can be used to perform pre-conditions
on a route then pass control to subsequent routes when there is no reason to proceed
with the route matched.
</p><p>The following snippet illustrates the most simple route definition possible. Express
translates the path strings to regular expressions, used internally to match incoming requests.
Query strings are <em>not</em> considered when peforming these matches, for example "GET /"
would match the following route, as would "GET /?name=tobi".
</p><pre class="js"><code>app.get('/', function(req, res){
res.send('hello world');
});
</code></pre><p>Regular expressions may also be used, and can be useful
if you have very specific restraints, for example the following
would match "GET /commits/71dbb9c" as well as "GET /commits/71dbb9c..4c084f9".
</p><pre class="js"><code>app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){
var from = req.params[0];
var to = req.params[1] || 'HEAD';
res.send('commit range ' + from + '..' + to);
});
</code></pre><p>Several callbacks may also be passed, useful for re-using middleware
that load resources, perform validations, etc.
</p><pre class="js"><code>app.get('/user/:id', user.load, function(){
// ...
})
</code></pre><p>These callbacks may be passed within arrays as well, these arrays are
simply flattened when passed:
</p><pre class="js"><code>var middleware = [loadForum, loadThread];
app.get('/forum/:fid/thread/:tid', middleware, function(){
// ...
})
app.post('/forum/:fid/thread/:tid', middleware, function(){
// ...
})</code></pre></section><section><h3 id="app.all">app.all(path, [callback...], callback)</h3><p>This method functions just like the <code>app.VERB()</code> methods,
however it matches all HTTP verbs.
</p><p>This method is extremely useful for
mapping "global" logic for specific path prefixes or arbitrary matches.
For example if you placed the following route at the top of all other
route definitions, it would require that all routes from that point on
would require authentication, and automatically load a user. Keep in mind
that these callbacks do not have to act as end points, <code>loadUser</code>
can perform a task, then <code>next()</code> to continue matching subsequent
routes.
</p><pre class="js"><code>app.all('*', requireAuthentication, loadUser);
</code></pre><p>Or the equivalent:
</p><pre class="js"><code>app.all('*', requireAuthentication)
app.all('*', loadUser);
</code></pre><p>Another great example of this is white-listed "global" functionality. Here
the example is much like before, however only restricting paths prefixed with
"/api":
</p><pre class="js"><code>app.all('/api/*', requireAuthentication);</code></pre></section><section><h3 id="app.locals">app.locals</h3><p>Application local variables are provided to all templates
rendered within the application. This is useful for providing
helper functions to templates, as well as app-level data.
</p><pre class="js"><code>app.locals.title = 'My App';
app.locals.strftime = require('strftime');
</code></pre><p>The <code>app.locals</code> object is a JavaScript <code>Function</code>,
which when invoked with an object will merge properties into itself, providing
a simple way to expose existing objects as local variables.
</p><pre class="js"><code>app.locals({
title: 'My App',
phone: '1-250-858-9990',
email: 'me@myapp.com'
});
app.locals.title
// => 'My App'
app.locals.email
// => 'me@myapp.com'
</code></pre><p>A consequence of the <code>app.locals</code> Object being ultimately a Javascript Function Object is that you must not reuse existing (native) named properties for your own variable names, such as <code>name, apply, bind, call, arguments, length, constructor</code>.
</p><pre class="js"><code>app.locals({name: 'My App'});
app.locals.name
// => return 'app.locals' in place of 'My App' (app.locals is a Function !)
// => if name's variable is used in a template, a ReferenceError will be returned.
</code></pre><p>The full list of native named properties can be found in many specifications. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference">JavaScript specification</a> introduced original properties, some of which still recognized by modern engines, and the <a href="http://www.ecma-international.org/ecma-262/5.1/">EcmaScript specification</a> then built on it and normalized the set of properties, adding new ones and removing deprecated ones. Check out properties for Functions and Objects if interested.
</p><p>By default Express exposes only a single app-level local variable, <code>settings</code>.
</p><pre class="js"><code>app.set('title', 'My App');
// use settings.title in a view</code></pre></section><section><h3 id="app.render">app.render(view, [options], callback)</h3><p>Render a <code>view</code> with a callback responding with
the rendered string. This is the app-level variant of <code>res.render()</code>,
and otherwise behaves the same way.
</p><pre class="js"><code>app.render('email', function(err, html){
// ...
});
app.render('email', { name: 'Tobi' }, function(err, html){
// ...
});</code></pre></section><section><h3 id="app.routes">app.routes</h3><p>The <code>app.routes</code> object houses all of the routes defined mapped
by the associated HTTP verb. This object may be used for introspection capabilities,
for example Express uses this internally not only for routing but to provide default
<string>OPTIONS</string> behaviour unless <code>app.options()</code> is used. Your application
or framework may also remove routes by simply by removing them from this object.
</p><pre class="js"><code>console.log(app.routes)
{ get:
[ { path: '/',
method: 'get',
callbacks: [Object],
keys: [],
regexp: /^\/\/?$/i },
{ path: '/user/:id',
method: 'get',
callbacks: [Object],
keys: [{ name: 'id', optional: false }],
regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ],
delete:
[ { path: '/user/:id',
method: 'delete',
callbacks: [Object],
keys: [Object],
regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ] }</code></pre></section><section><h3 id="app.listen">app.listen()</h3><p>Bind and listen for connections on the given host and port,
this method is identical to node's <a href="http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback">http.Server#listen()</a>.
</p><pre class="js"><code>var express = require('express');
var app = express();
app.listen(3000);
</code></pre><p>The <code>app</code> returned by <code>express()</code> is in fact a JavaScript
<code>Function</code>, designed to be passed to node's http servers as a callback
to handle requests. This allows you to provide both HTTP and HTTPS versions of
your app with the same codebase easily, as the app does not inherit from these,
it is simply a callback:
</p><pre class="js"><code>var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
</code></pre><p>The <code>app.listen()</code> method is simply a convenience method defined as,
if you wish to use HTTPS or provide both, use the technique above.
</p><pre class="js"><code>app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};</code></pre></section><h2>Request</h2><a name="request"></a><section><h3 id="req.params">req.params</h3><p>This property is an array containing properties mapped to the named route "parameters".
For example if you have the route <code>/user/:name</code>, then the "name" property
is available to you as <code>req.params.name</code>. This object defaults to <code>{}</code>.
</p><pre class="js"><code>// GET /user/tj
req.params.name
// => "tj"
</code></pre><p>When a regular expression is used for the route definition, capture groups
are provided in the array using <code>req.params[N]</code>, where <code>N</code>
is the nth capture group. This rule is applied to unnamed wild-card matches
with string routes such as `/file/*`:
</p><pre class="js"><code>// GET /file/javascripts/jquery.js
req.params[0]
// => "javascripts/jquery.js"</code></pre></section><section><h3 id="req.query">req.query</h3><p>This property is an object containing the parsed query-string,
defaulting to <code>{}</code>.
</p><pre class="js"><code>// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"</code></pre></section><section><h3 id="req.body">req.body</h3><p>This property is an object containing the parsed request body. This feature
is provided by the <code>bodyParser()</code> middleware, though other body
parsing middleware may follow this convention as well. This property
defaults to <code>{}</code> when <code>bodyParser()</code> is used.
</p><pre class="js"><code>// POST user[name]=tobi&user[email]=tobi@learnboost.com
req.body.user.name
// => "tobi"
req.body.user.email
// => "tobi@learnboost.com"
// POST { "name": "tobi" }
req.body.name
// => "tobi"</code></pre></section><section><h3 id="req.files">req.files</h3><p>This property is an object of the files uploaded. This feature
is provided by the <code>bodyParser()</code> middleware, though other body
parsing middleware may follow this convention as well. This property
defaults to <code>{}</code> when <code>bodyParser()</code> is used.
</p><p>For example if a <strong>file</strong> field was named "image",
and a file was uploaded, <code>req.files.image</code> would contain
the following <code>File</code> object:
</p><pre class="js"><code>{ size: 74643,
path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876',
name: 'edge.png',
type: 'image/png',
hash: false,
lastModifiedDate: Thu Aug 09 2012 20:07:51 GMT-0700 (PDT),
_writeStream:
{ path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876',
fd: 13,
writable: false,
flags: 'w',
encoding: 'binary',
mode: 438,
bytesWritten: 74643,
busy: false,
_queue: [],
_open: [Function],
drainable: true },
length: [Getter],
filename: [Getter],
mime: [Getter] }
</code></pre><p>The <code>bodyParser()</code> middleware utilizes the
<a href="https://github.com/felixge/node-formidable">node-formidable</a>
module internally, and accepts the same options. An example of this
is the <code>keepExtensions</code> formidable option, defaulting to <strong>false</strong>
which in this case gives you the filename "/tmp/8ef9c52abe857867fd0a4e9a819d1876" void of
the ".png" extension. To enable this, and others you may pass them to <code>bodyParser()</code>:
</p><pre class="js"><code>app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' }));</code></pre></section><section><h3 id="req.param">req.param(name)</h3><p>Return the value of param <code>name</code> when present.
</p><pre class="js"><code>// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"
</code></pre><p>Lookup is performed in the following order:</p><ul><li><code>req.params</code></li><li><code>req.body</code></li><li><code>req.query</code></li></ul><p>Direct access to <code>req.body</code>, <code>req.params</code>,
and <code>req.query</code> should be favoured for clarity - unless
you truly accept input from each object.</p></section><section><h3 id="req.route">req.route</h3><p>The currently matched <code>Route</code> containing
several properties such as the route's original path
string, the regexp generated, and so on.
</p><pre class="js"><code>app.get('/user/:id?', function(req, res){
console.log(req.route);
});
</code></pre><p>Example output from the previous snippet:
</p><pre class="js"><code>{ path: '/user/:id?',
method: 'get',
callbacks: [ [Function] ],
keys: [ { name: 'id', optional: true } ],
regexp: /^\/user(?:\/([^\/]+?))?\/?$/i,
params: [ id: '12' ] }</code></pre></section><section><h3 id="req.cookies">req.cookies</h3><p>When the <code>cookieParser()</code> middleware is used this object
defaults to <code>{}</code>, otherwise contains the cookies sent by
the user-agent.
</p><pre class="js"><code>// Cookie: name=tj
req.cookies.name
// => "tj"</code></pre></section><section><h3 id="req.signedCookies">req.signedCookies</h3><p>When the <code>cookieParser(secret)</code> middleware is used this object
defaults to <code>{}</code>, otherwise contains the signed cookies sent by
the user-agent, unsigned and ready for use. Signed cookies reside in a different
object to show developer intent, otherwise a malicious attack could be
placed on `req.cookie` values which are easy to spoof. Note that signing
a cookie does not mean it is "hidden" nor encrypted, this simply prevents
tampering as the secret used to sign is private.
</p><pre class="js"><code>// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
req.signedCookies.user
// => "tobi"</code></pre></section><section><h3 id="req.get">req.get(field)</h3><p>
Get the case-insensitive request header <code>field</code>.
The <em>Referrer</em> and <em>Referer</em> fields are interchangeable.</p><pre class="js"><code>req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined
</code></pre><p>Aliased as <code>req.header(field)</code>.</p></section><section><h3 id="req.accepts">req.accepts(types)</h3><p>Check if the given <code>types</code> are acceptable, returning
the best match when true, otherwise <code>undefined</code> - in which
case you should respond with 406 "Not Acceptable".
</p><p>The <code>type</code> value may be a single mime type string
such as "application/json", the extension name
such as "json", a comma-delimited list or an array. When a list
or array is given the <em>best</em> match, if any is returned.
</p><pre class="js"><code>// Accept: text/html
req.accepts('html');
// => "html"
// Accept: text/*, application/json
req.accepts('html');
// => "html"
req.accepts('text/html');
// => "text/html"
req.accepts('json, text');
// => "json"
req.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
req.accepts('image/png');
req.accepts('png');
// => undefined
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
req.accepts('html, json');
// => "json"</code></pre></section><section><h3 id="req.accepted">req.accepted</h3><p>Return an array of Accepted media types ordered from highest quality to lowest.
</p><pre class="js"><code>[ { value: 'application/json',
quality: 1,
type: 'application',
subtype: 'json' },
{ value: 'text/html',
quality: 0.5,
type: 'text',
subtype: 'html' } ]</code></pre></section><section><h3 id="req.is">req.is(type)</h3><p>Check if the incoming request contains the "Content-Type"
header field, and it matches the give mime <code>type</code>.
</p><pre class="js"><code>// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true
// When Content-Type is application/json
req.is('json');
req.is('application/json');
req.is('application/*');
// => true
req.is('html');
// => false</code></pre></section><section><h3 id="req.ip">req.ip</h3><p>Return the remote address, or when "trust proxy"
is enabled - the upstream address.
</p><pre class="js"><code>req.ip
// => "127.0.0.1"</code></pre></section><section><h3 id="req.ips">req.ips</h3><p>When "trust proxy" is `true`, parse
the "X-Forwarded-For" ip address list
and return an array, otherwise an empty
array is returned.
For example if the value were "client, proxy1, proxy2"
you would receive the array <code>["client", "proxy1", "proxy2"]</code>
where "proxy2" is the furthest down-stream.</p></section><section><h3 id="req.path">req.path</h3><p>Returns the request URL pathname.
</p><pre class="js"><code>// example.com/users?sort=desc
req.path
// => "/users"</code></pre></section><section><h3 id="req.host">req.host</h3><p>Returns the hostname from the "Host" header field (void of portno).
</p><pre class="js"><code>// Host: "example.com:3000"
req.host
// => "example.com"</code></pre></section><section><h3 id="req.fresh">req.fresh</h3><p>Check if the request is fresh - aka Last-Modified and/or the ETag still match,
indicating that the resource is "fresh".
</p><pre class="js"><code>req.fresh
// => true</code></pre></section><section><h3 id="req.stale">req.stale</h3><p>Check if the request is stale - aka Last-Modified and/or the ETag do not match,
indicating that the resource is "stale".
</p><pre class="js"><code>req.stale
// => true</code></pre></section><section><h3 id="req.xhr">req.xhr</h3><p>Check if the request was issued with the "X-Requested-With"
header field set to "XMLHttpRequest" (jQuery etc).
</p><pre class="js"><code>req.xhr
// => true</code></pre></section><section><h3 id="req.protocol">req.protocol</h3><p>Return the protocol string "http" or "https"
when requested with TLS. When the "trust proxy"
setting is enabled the "X-Forwarded-Proto" header
field will be trusted. If you're running behind
a reverse proxy that supplies https for you this
may be enabled.
</p><pre class="js"><code>req.protocol
// => "http"</code></pre></section><section><h3 id="req.secure">req.secure</h3><p>Check if a TLS connection is established. This is a short-hand for:
</p><pre class="js"><code>'https' == req.protocol;</code></pre></section><section><h3 id="req.subdomains">req.subdomains</h3><p>Return subdomains as an array.
</p><pre class="js"><code>// Host: "tobi.ferrets.example.com"
req.subdomains
// => ["ferrets", "tobi"]</code></pre></section><section><h3 id="req.originalUrl">req.originalUrl</h3><p>This property is much like <code>req.url</code>, however it retains
the original request url, allowing you to rewrite <code>req.url</code>
freely for internal routing purposes. For example the "mounting" feature
of <a href="#app.use">app.use()</a> will rewrite <code>req.url</code> to
strip the mount point.
</p><pre class="js"><code>// GET /search?q=something
req.originalUrl
// => "/search?q=something"</code></pre></section><section><h3 id="req.acceptedLanguages">req.acceptedLanguages</h3><p>Return an array of Accepted languages ordered from highest quality to lowest.
</p><pre class="js"><code>Accept-Language: en;q=.5, en-us
// => ['en-us', 'en']</code></pre></section><section><h3 id="req.acceptedCharsets">req.acceptedCharsets</h3><p>Return an array of Accepted charsets ordered from highest quality to lowest.
</p><pre class="js"><code>Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8
// => ['unicode-1-1', 'iso-8859-5']</code></pre></section><section><h3 id="req.acceptsCharset">req.acceptsCharset(charset)</h3><p>Check if the given <code>charset</code> are acceptable.</p></section><section><h3 id="req.acceptsLanguage">req.acceptsLanguage(lang)</h3><p>Check if the given <code>lang</code> are acceptable.</p></section><h2>Response</h2><a name="response"></a><section><h3 id="res.status">res.status(code)</h3><p>Chainable alias of node's <code>res.statusCode=</code>.
</p><pre class="js"><code>res.status(404).sendfile('path/to/404.png');</code></pre></section><section><h3 id="res.set">res.set(field, [value])</h3><p>
Set header <code>field</code> to <code>value</code>,
or pass an object to set multiple fields at once.</p><pre class="js"><code>res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
</code></pre><p>Aliased as <code>res.header(field, [value])</code>.</p></section><section><h3 id="res.get">res.get(field)</h3><p>
Get the case-insensitive response header <code>field</code>. </p><pre class="js"><code>res.get('Content-Type');
// => "text/plain"</code></pre></section><section><h3 id="res.cookie">res.cookie(name, value, [options])</h3><p>Set cookie <code>name</code> to <code>value</code>, which may be a string or object converted to JSON. The <code>path</code>
option defaults to "/".
</p><pre class="js"><code>res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
</code></pre><p>The <code>maxAge</code> option is a convenience option for setting "expires"
relative to the current time in milliseconds. The following is equivalent to
the previous example.
</p><pre class="js"><code>res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
</code></pre><p>An object may be passed which is then serialized as JSON, which is
automatically parsed by the <code>bodyParser()</code> middleware.
</p><pre class="js"><code>res.cookie('cart', { items: [1,2,3] });
res.cookie('cart', { items: [1,2,3] }, { maxAge: 900000 });
</code></pre><p>Signed cookies are also supported through this method. Simply
pass the <code>signed</code> option. When given <code>res.cookie()</code>
will use the secret passed to <code>express.cookieParser(secret)</code>
to sign the value.
</p><pre class="js"><code>res.cookie('name', 'tobi', { signed: true });
</code></pre><p>Later you may access this value through the <a href="#req.signedCookies">req.signedCookie</a>
object.</p></section><section><h3 id="res.clearCookie">res.clearCookie(name, [options])</h3><p>Clear cookie <code>name</code>. The <code>path</code>
option defaults to "/".
</p><pre class="js"><code>res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });</code></pre></section><section><h3 id="res.redirect">res.redirect([status], url)</h3><p>Redirect to the given <code>url</code> with optional <code>status</code> code
defaulting to 302 "Found".
</p><pre class="js"><code>res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');
</code></pre><p>Express supports a few forms of redirection, first being
a fully qualified URI for redirecting to a different site:
</p><pre class="js"><code>res.redirect('http://google.com');
</code></pre><p>The second form is the pathname-relative redirect, for example
if you were on <code>http://example.com/admin/post/new</code>, the
following redirect to <code>/admin</code> would land you at <code>http://example.com/admin</code>:
</p><pre class="js"><code>res.redirect('/admin');
</code></pre><p>This next redirect is relative to the <code>mount</code> point of the application. For example
if you have a blog application mounted at <code>/blog</code>, ideally it has no knowledge of
where it was mounted, so where a redirect of <code>/admin/post/new</code> would simply give you
<code>http://example.com/admin/post/new</code>, the following mount-relative redirect would give
you <code>http://example.com/blog/admin/post/new</code>:
</p><pre class="js"><code>res.redirect('admin/post/new');
</code></pre><p>Pathname relative redirects are also possible. If you were
on <code>http://example.com/admin/post/new</code>, the following redirect
would land you at <code>http//example.com/admin/post</code>:
</p><pre class="js"><code>res.redirect('..');
</code></pre><p>The final special-case is a <code>back</code> redirect, redirecting back to
the Referer (or Referrer), defaulting to <code>/</code> when missing.
</p><pre class="js"><code>res.redirect('back');
</code></pre></section><section><h3 id="res.location">res.location</h3><p>Set the location header.
</p><pre class="js"><code>res.location('/foo/bar');
res.location('foo/bar');
res.location('http://example.com');
res.location('../login');
res.location('back');
</code></pre><p>You can use the same kind of <code>urls</code> as in
<code>res.redirect()</code>.
</p><p>For example, if your application is mounted at <code>/blog</code>,
the following would set the <code>location</code> header to
<code>/blog/admin</code>:
</p><pre class="js"><code>res.location('admin')</code></pre></section><section><h3 id="res.charset">res.charset</h3><p>Assign the charset. Defaults to "utf-8".
</p><pre class="js"><code>res.charset = 'value';
res.send('<p>some html</p>');
// => Content-Type: text/html; charset=value</code></pre></section><section><h3 id="res.send">res.send([body|status], [body])</h3><p>Send a response.
</p><pre class="js"><code>res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.send(404, 'Sorry, we cannot find that!');
res.send(500, { error: 'something blew up' });
res.send(200);
</code></pre><p>This method performs a myriad of
useful tasks for simple non-streaming responses such
as automatically assigning the Content-Length unless
previously defined and providing automatic <em>HEAD</em> and
HTTP cache freshness support.
</p><p>When a <code>Buffer</code> is given
the Content-Type is set to "application/octet-stream"
unless previously defined as shown below:
</p><pre class="js"><code>res.set('Content-Type', 'text/html');
res.send(new Buffer('<p>some html</p>'));
</code></pre><p>When a <code>String</code> is given the
Content-Type is set defaulted to "text/html":
</p><pre class="js"><code>res.send('<p>some html</p>');
</code></pre><p>When an <code>Array</code> or <code>Object</code> is
given Express will respond with the JSON representation:
</p><pre class="js"><code>res.send({ user: 'tobi' })
res.send([1,2,3])
</code></pre><p>Finally when a <code>Number</code> is given without
any of the previously mentioned bodies, then a response
body string is assigned for you. For example 200 will
respond will the text "OK", and 404 "Not Found" and so on.
</p><pre class="js"><code>res.send(200)
res.send(404)
res.send(500)</code></pre></section><section><h3 id="res.json">res.json([status|body], [body])</h3><p>Send a JSON response. This method is identical
to <code>res.send()</code> when an object or
array is passed, however it may be used for
explicit JSON conversion of non-objects (null, undefined, etc),
though these are technically not valid JSON.
</p><pre class="js"><code>res.json(null)
res.json({ user: 'tobi' })
res.json(500, { error: 'message' })</code></pre></section><section><h3 id="res.jsonp">res.jsonp([status|body], [body])</h3><p>Send a JSON response with JSONP support. This method is identical
to <code>res.json()</code> however opts-in to JSONP callback
support.
</p><pre class="js"><code>res.jsonp(null)
// => null
res.jsonp({ user: 'tobi' })
// => { "user": "tobi" }
res.jsonp(500, { error: 'message' })
// => { "error": "message" }
</code></pre><p>By default the JSONP callback name is simply <code>callback</code>,
however you may alter this with the <a href="#app-settings">jsonp callback name</a>
setting. The following are some examples of JSONP responses using the same
code:
</p><pre class="js"><code>// ?callback=foo
res.jsonp({ user: 'tobi' })
// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb');
// ?cb=foo
res.jsonp(500, { error: 'message' })
// => foo({ "error": "message" })</code></pre></section><section><h3 id="res.type">res.type(type)</h3><p>Sets the Content-Type to the mime lookup of <code>type</code>,
or when "/" is present the Content-Type is simply set to this
literal value.
</p><pre class="js"><code>res.type('.html');
res.type('html');
res.type('json');
res.type('application/json');
res.type('png');</code></pre></section><section><h3 id="res.format">res.format(object)</h3><p>Performs content-negotiation on the request Accept header
field when present. This method uses <code>req.accepted</code>, an array of
acceptable types ordered by their quality values, otherwise the
first callback is invoked. When no match is performed the server
responds with 406 "Not Acceptable", or invokes the <code>default</code>
callback.
</p><p>The Content-Type is set for you when a callback is selected,
however you may alter this within the callback using <code>res.set()</code>
or <code>res.type()</code> etcetera.
</p><p>The following example would respond with <code>{ "message": "hey" }</code>
when the Accept header field is set to "application/json" or "*/json",
however if "*/*" is given then "hey" will be the response.
</p><pre class="js"><code>res.format({
'text/plain': function(){
res.send('hey');
},
'text/html': function(){
res.send('<p>hey</p>');
},
'application/json': function(){
res.send({ message: 'hey' });
}
});
</code></pre><p>In addition to canonicalized MIME types you may also
use extnames mapped to these types, providing a slightly
less verbose implementation:
</p><pre class="js"><code>res.format({
text: function(){
res.send('hey');
},
html: function(){
res.send('<p>hey</p>');
},
json: function(){
res.send({ message: 'hey' });
}
});</code></pre></section><section><h3 id="res.attachment">res.attachment([filename])</h3><p>Sets the Content-Disposition header field to "attachment". If
a <code>filename</code> is given then the Content-Type will be
automatically set based on the extname via <code>res.type()</code>,
and the Content-Disposition's "filename=" parameter will be set.
</p><pre class="js"><code>res.attachment();
// Content-Disposition: attachment
res.attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png</code></pre></section><section><h3 id="res.sendfile">res.sendfile(path, [options], [fn]])</h3><p>Transfer the file at the given <code>path</code>.</p><p>Automatically defaults the Content-Type response header field based
on the filename's extension. The callback <code>fn(err)</code> is
invoked when the transfer is complete or when an error occurs.
</p><p>Options:</p><ul><li><code>maxAge</code> in milliseconds defaulting to 0</li><li><code>root</code> root directory for relative filenames</li></ul><p>This method provides fine-grained support for file serving
as illustrated in the following example:
</p><pre class="js"><code>app.get('/user/:uid/photos/:file', function(req, res){
var uid = req.params.uid
, file = req.params.file;
req.user.mayViewFilesFrom(uid, function(yes){
if (yes) {
res.sendfile('/uploads/' + uid + '/' + file);
} else {
res.send(403, 'Sorry! you cant see that.');
}
});
});</code></pre></section><section><h3 id="res.download">res.download(path, [filename], [fn])</h3><p>Transfer the file at <code>path</code> as an "attachment",
typically browsers will prompt the user for download. The
Content-Disposition "filename=" parameter, aka the one
that will appear in the brower dialog is set to <code>path</code>
by default, however you may provide an override <code>filename</code>.
</p><p>When an error has ocurred or transfer is complete the optional
callback <code>fn</code> is invoked. This method uses <a href="#res.sendfile">res.sendfile()</a>
to transfer the file.
</p><pre class="js"><code>res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', function(err){
if (err) {
// handle error, keep in mind the response may be partially-sent
// so check res.headerSent
} else {
// decrement a download credit etc
}
});</code></pre></section><section><h3 id="res.links">res.links(links)</h3><p>Join the given <code>links</code> to populate the "Link"
response header field.
</p><pre class="js"><code>res.links({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5'
});
</code></pre><p>yields:</p><pre><code>Link: <http://api.example.com/users?page=2>; rel="next",
<http://api.example.com/users?page=5>; rel="last"</code></pre></section><section><h3 id="res.locals">res.locals</h3><p>Response local variables are scoped to the request, thus only
available to the view(s) rendered during that request / response
cycle, if any. Otherwise this API is identical to <a href="#app.locals">app.locals</a>.
</p><p>This object is useful for exposing request-level information such as the
request pathname, authenticated user, user settings etcetera.
</p><pre class="js"><code>app.use(function(req, res, next){
res.locals.user = req.user;
res.locals.authenticated = ! req.user.anonymous;
next();
});</code></pre></section><section><h3 id="res.render">res.render(view, [locals], callback)</h3><p>Render a <code>view</code> with a callback responding with
the rendered string. When an error occurs <code>next(err)</code>
is invoked internally. When a callback is provided both the possible error
and rendered string are passed, and no automated response is performed.
</p><pre class="js"><code>res.render('index', function(err, html){
// ...
});
res.render('user', { name: 'Tobi' }, function(err, html){
// ...
});</code></pre></section><h2>Middleware</h2><a name="middleware"></a><section><h3 id="basicAuth">basicAuth()</h3><p>Basic Authentication middleware, populating <code>req.user</code>
with the username.
</p><p>Simple username and password:</p><pre class="js"><code>app.use(express.basicAuth('username', 'password'));
</code></pre><p>Callback verification:</p><pre class="js"><code>app.use(express.basicAuth(function(user, pass){
return 'tj' == user && 'wahoo' == pass;
}));
</code></pre><p>Async callback verification, accepting <code>fn(err, user)</code>,
in this case <code>req.user</code> will be the user object passed.
</p><pre class="js"><code>app.use(express.basicAuth(function(user, pass, fn){
User.authenticate({ user: user, pass: pass }, fn);
}))</code></pre></section><section><h3 id="bodyParser">bodyParser()</h3><p>Request body parsing middleware supporting JSON, urlencoded,
and multipart requests. This middleware is simply a wrapper
for the <code>json()</code>, <code>urlencoded()</code>, and
<code>multipart()</code> middleware.
</p><pre class="js"><code>app.use(express.bodyParser());
// is equivalent to:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
</code></pre><p>For security sake, it's better to disable file upload if your application
doesn't need it. To do this, use only the needed middleware, i.e. don't use
the <code>bodyParser</code> and <code>multipart()</code> middleware:
</p><pre class="js"><code>app.use(express.json());
app.use(express.urlencoded());
</code></pre><p>If your application needs file upload you should set up
<a href='https://groups.google.com/d/msg/express-js/iP2VyhkypHo/5AXQiYN3RPcJ'>a strategy for dealing with those files</a>.</p></section><section><h3 id="compress">compress()</h3><p>Compress response data with gzip / deflate. This middleware
should be placed "high" within the stack to ensure all
responses may be compressed.
</p><pre class="js"><code>app.use(express.logger());
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.bodyParser());</code></pre></section><section><h3 id="cookieParser">cookieParser()</h3><p>Parses the Cookie header field and populates <code>req.cookies</code>
with an object keyed by the cookie names. Optionally you may enabled
signed cookie support by passing a <code>secret</code> string.
</p><pre class="js"><code>app.use(express.cookieParser());
app.use(express.cookieParser('some secret'));</code></pre></section><section><h3 id="cookieSession">cookieSession()</h3><p>Provides cookie-based sessions, and populates <code>req.session</code>.
This middleware takes the following options:
</p><ul><li><code>key</code> cookie name defaulting to <code>connect.sess</code></li><li><code>secret</code> prevents cookie tampering</li><li><code>cookie</code> session cookie settings, defaulting to <code>{ path: '/', httpOnly: true, maxAge: null }</code></li><li><code>proxy</code> trust the reverse proxy when setting secure cookies (via "x-forwarded-proto")</li></ul><pre class="js"><code>app.use(express.cookieSession());
</code></pre><p>To clear a cookie simply assign the session to null before responding:</p><pre class="js"><code>req.session = null</code></pre></section><section><h3 id="csrf">csrf()</h3><p>CSRF protection middleware.
</p><p>By default this middleware generates a token named "_csrf"
which should be added to requests which mutate
state, within a hidden form field, query-string etc. This
token is validated against <code>req.csrfToken()</code>.
</p><p>The default <code>value</code> function checks <code>req.body</code> generated
by the <code>bodyParser()</code> middleware, <code>req.query</code> generated
by <code>query()</code>, and the "X-CSRF-Token" header field.
</p><p>This middleware requires session support, thus should be added
somewhere below <code>session()</code>.</p></section><section><h3 id="directory">directory()</h3><p>Directory serving middleware, serves the given <code>path</code>.
This middleware may be paired with <code>static()</code> to serve
files, providing a full-featured file browser.
</p><pre class="js"><code>app.use(express.directory('public'))
app.use(express.static('public'))
</code></pre><p>This middleware accepts the following options:
</p><ul><li><code>hidden</code> display hidden (dot) files. Defaults to false.</li><li><code>icons</code> display icons. Defaults to false.</li><li><code>filter</code> Apply this filter function to files. Defaults to false.</li></ul></section><!--include ./mw-errorHandler--><!--include ./mw-favicon--><!--include ./mw-json--><!--include ./mw-limit--><!--include ./mw-logger--><!--include ./mw-methodOverride--><!--include ./mw-multipart--><!--include ./mw-query--><!--include ./mw-responseTime--><!--include ./mw-static--><!--include ./mw-timeout--><!--include ./mw-urlencoded--><!--include ./mw-vhost--></div></section><script>var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-25235225-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script><a id="top" href="#"><img src="images/arrow.png"></a><footer><div id="footer-content">© 2012 TJ Holowaychuk. All rights reserved.</div></footer></body></html>