forked from expressjs/expressjs.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.html
1392 lines (1280 loc) · 82.8 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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html><html><head><title>Express - api reference</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/css/style.css"><link rel="stylesheet" href="/css/dropit.css"><link rel="stylesheet" href="/css/prism.css"><link rel="stylesheet" href="/css/font-awesome.min.css"><link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;subset=latin,latin-ext"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script data-cfasync="false" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script data-cfasync="false" src="/js/app.js?v=06112014"></script><script data-cfasync="false" src="/js/retina.js"></script><script data-cfasync="false" src="/js/dropit.js"></script><script data-cfasync="false" src="/js/prism.js"></script></head><body><section class="content"><header><div id="mobile-menu"><div id="nav-button" class="fa fa-bars fa-2x button"></div></div><section id="logo"><a href="/" class="express">Express</a></section><div id="navbar"><ul id="navmenu"><li><a href="/" id="home-menu">Home</a></li><li><ul id="getting-started-menu" class="menu"><li><a href="/starter/installing.html">Getting started</a><ul><li><a href="/starter/installing.html">Installing</a></li><li><a href="/starter/generator.html">Express generator</a></li><li><a href="/starter/hello-world.html">Hello world</a></li><li><a href="/starter/basic-routing.html">Basic routing</a></li><li><a href="/starter/faq.html">FAQ</a></li></ul></li></ul></li><li><ul id="guide-menu" class="menu"><li><a href="/guide/error-handling.html">Guide</a><ul><li><a href="/guide/error-handling.html">Error handling</a></li><li><a href="/guide/debugging.html">Debugging Express</a></li><li><a href="/guide/behind-proxies.html">Express behind proxies</a></li><li><a href="/guide/migrating-4.html">Moving to Express 4</a></li><li><a href="/guide/using-middleware.html">Using middleware</a></li><li><a href="/guide/using-template-engines.html">Using template engines</a></li></ul></li></ul></li><li><ul id="application-menu" class="menu"><li><a href="/4x/api.html" class="active">API reference</a><ul><li><a href="/4x/api.html">4.x</a></li><li><a href="/3x/api.html">3.x</a></li><li><a href="/2x/">2.x (deprecated)</a></li></ul></li></ul></li><li><ul id="advanced-topics-menu" class="menu"><li><a href="/advanced/developing-template-engines.html">Advanced topics</a><ul><li><a href="/advanced/developing-template-engines.html">Template engines</a></li><li><a href="/advanced/security-updates.html">Security updates</a></li></ul></li></ul></li><li><ul id="resources-menu" class="menu"><li><a href="/resources/glossary.html">Resources</a><ul><li><a href="/resources/glossary.html">Glossary</a></li><li><a href="/resources/middleware.html">Middleware</a></li><li><a href="/resources/community.html">Community</a></li><li><a href="/resources/books-blogs.html">Books and blogs</a></li><li><a href="/resources/applications.html">Applications</a></li></ul></li></ul></li></ul></div><a href="http://strongloop.com/node-js/training/" title="Node and Express Training from StrongLoop" id="strongloop-header">Express and Node.js Training from StrongLoop</a></header><ul id="menu"><li id="app-api"><a href="#application">Application</a><ul id="app-menu"><li><a href="#express">express()</a></li><li><a href="#app-settings">application settings</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.use">app.use()</a></li><li><a href="#app.engine">app.engine()</a></li><li><a href="#app.param">app.param()</a></li><li><a href="#app.METHOD">application routing</a></li><li><a href="#app.all">app.all()</a></li><li><a href="#app.route">app.route()</a></li><li><a href="#app.locals">app.locals</a></li><li><a href="#app.render">app.render()</a></li><li><a href="#app.listen">app.listen()</a></li><li><a href="#app.path">app.path()</a></li><li><a href="#app.mountpath">app.mountpath</a></li><li><a href="#app.onmount">app.onmount</a></li></ul></li><li id="req-api"><a href="#request">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.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.acceptsCharsets">req.acceptsCharsets()</a></li><li><a href="#req.acceptsLanguages">req.acceptsLanguages()</a></li><li><a href="#req.acceptsEncodings">req.acceptsEncodings()</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.hostname">req.hostname</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.baseUrl">req.baseUrl</a></li></ul></li><li id="res-api"><a href="#response">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.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.sendStatus">res.sendStatus()</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><li><a href="#res.vary">res.vary()</a></li><li><a href="#res.end">res.end()</a></li><li><a href="#res.headersSent">res.headersSent</a></li></ul></li><li id="router-api"><a href="#router">Router</a><ul id="router-menu"><li><a href="#router">Router()</a></li><li><a href="#router.use">router.use()</a></li><li><a href="#router.param">router.param()</a></li><li><a href="#router.route">router.route()</a></li><li><a href="#router.METHOD">router.METHOD()</a></li><li><a href="#router.all">router.all()</a></li></ul></li><li id="middleware-api"><a href="#middleware">Middleware</a><ul id="middleware-menu"><li><a href="#middleware.api">API</a></li><li><a href="#middleware.application">Application level</a></li><li><a href="#middleware.router">Router level</a></li><li><a href="#middleware.thirdparty">Third-party</a></li><li><a href="#middleware.builtin">Built-in</a></li></ul></li></ul><div id="overlay"></div><div id="api-doc"><h1>4.x API</h1><h2>Application</h2><a id="application" class="h2"></a><section><h3 id="express">express()</h3><p>Create an express application.</p>
<pre><code class="lang-js">var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
</code></pre>
</section><section><h3 id="app-settings">settings</h3><p>Express application settings can be set using <a href="#app.set"><code>app.set()</code></a>, and retrieved using <a href="#app.get"><code>app.get()</code></a>. The following settings will alter how the app behaves:</p>
<ul>
<li><p><code>trust proxy</code> Indicate that the app is sitting behind a front-facing proxy, and the <code>X-Forwarded-*</code> headers may be trusted for determining the connection and the IP address of the client. It must, however, be noted that, the <code>X-Forwarded-*</code> headers are easily spoofed and the detected IP addresses are unreliable.</p>
<p><code>trust proxy</code> is disabled by default. When enabled, Express attempts to determine the IP address of the client which is connected through the front-facing proxy, or a series of proxies. The <code>req.ips</code> property, then, contains an array of IP addresses the client is connected through. It can be enabled using either of the following values.</p>
<table class="doctable" border="1">
<thead><tr><th>Type</th><th>Value</th></tr></thead>
<tbody>
<tr>
<td><strong> Boolean </strong></td>
<td>
If <code>true</code>, the client's IP address is understood as the left-most entry in the <code>X-Forwarded-*</code> header.<br>
If <code>false</code>, the app is understood as directly facing the Internet and the client's IP address is derived from <code>req.connection.remoteAddress</code>. This is the default setting.
</td>
</tr>
<tr>
<td><strong> IP addresses </strong></td>
<td>
An IP address, subnet, or an array of IP addresses, and subnets to trust. The following is the list of pre-configured subnet names.
<ul>
<li>loopback - <code>127.0.0.1/8</code>, <code>::1/128</code></li>
<li>linklocal - <code>169.254.0.0/16</code>, <code>fe80::/10</code></li>
<li>uniquelocal - <code>10.0.0.0/8</code>, <code>172.16.0.0/12</code>, <code>192.168.0.0/16</code>, <code>fc00::/7</code></li>
</ul>
The IP addresses can be set in the following ways.<br>
<pre><code class="lang-js">app.set('trust proxy', 'loopback') // specify a single subnet
app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address
app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array</code></pre>
When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address.
</td>
</tr>
<tr>
<td><strong> Number </strong></td>
<td>Trust the <code>n</code>th hop from the front-facing proxy server as the client.</td>
</tr>
<tr>
<td><strong> Function </strong></td>
<td> Custom trust implementation. Use this only if you know what you are doing.
<pre><code class="lang-js">app.set('trust proxy', function (ip) {
if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs
else return false;
})</code></pre>
</tr>
</tbody>
</table>
<p>The <code>trust proxy</code> setting is implemented using the <a href="https://www.npmjs.org/package/proxy-addr">proxy-addr</a> package, look up its documentation for further details.</p>
</li>
<li><code>env</code> Environment mode, defaults to <code>process.env.NODE_ENV</code> (<code>NODE_ENV</code> environment variable) or "development".</li>
<li><code>subdomain offset</code> The number of dot-separated parts of the host to remove to access subdomain, two 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, <code>null</code> by default.</li>
<li><code>json spaces</code> When set, sends prettified JSON string indented with the specified amount of spaces. Disabled by default.</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 <code>"process.cwd() + '/views'"</code>.</li>
<li><code>query parser</code> The query parser to use - "simple" or "extended", defaults to "extended". The simple query parser is based on node's native query parser, <a href="http://nodejs.org/api/querystring.html">querystring</a>. The extended query parser is based on <a href="https://www.npmjs.org/package/qs">qs</a>.</li>
<li><code>x-powered-by</code> Enables the "X-Powered-By: Express" HTTP header, enabled by default.</li>
<li><p><code>etag</code> Set the ETag response header.</p>
<table class="doctable" border="1">
<thead><tr><th>Type</th><th>Value</th></tr></thead>
<tbody>
<tr>
<td><strong> Boolean </strong></td>
<td>
<code>true</code> enables strong ETag. This is the default setting.<br>
<code>false</code> disables ETag altogether.
</td>
</tr>
<tr>
<td><strong> String </strong></td>
<td>
If "strong", enables strong ETag.<br>
If "weak", enables weak ETag.
</td>
</tr>
<tr>
<td><strong> Function </strong></td>
<td> Custom ETag function implementation. Use this only if you know what you are doing.
<pre><code class="lang-js">app.set('etag', function (body, encoding) {
return generateHash(body, encoding); // consider the function is defined
})</code></pre>
</td>
</tr>
</tbody>
</table>
<p><a href="http://en.wikipedia.org/wiki/HTTP_ETag">More about the HTTP ETag header</a>.</p>
</li>
</ul>
</section><section><h3 id="app.set">app.set(name, value)</h3><p>Assigns setting <code>name</code> to <code>value</code>.</p>
<pre><code class="lang-js">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><code class="lang-js">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><code class="lang-js">app.enable('trust proxy');
app.get('trust proxy');
// => true
</code></pre>
</section><section><h3 id="app.enabled">app.enabled(name)</h3><p>Check if setting <code>name</code> is enabled.</p>
<pre><code class="lang-js">app.enabled('trust proxy');
// => false
app.enable('trust proxy');
app.enabled('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><code class="lang-js">app.disable('trust proxy');
app.get('trust proxy');
// => false
</code></pre>
</section><section><h3 id="app.disabled">app.disabled(name)</h3><p>Check if setting <code>name</code> is disabled.</p>
<pre><code class="lang-js">app.disabled('trust proxy');
// => true
app.enable('trust proxy');
app.disabled('trust proxy');
// => false
</code></pre>
</section><section><h3 id="app.use">app.use([path], [function...], function)</h3><p>Mount the <a href="#middleware.api">middleware</a> <code>function</code>(s) at the <code>path</code>. If <code>path</code> is not specified, it defaults to "/".</p>
<p>Mounting a middleware at a <code>path</code> will cause the middleware function to be executed whenever the base of the requested path matches the <code>path</code>.</p>
<p>Since <code>path</code> defaults to "/", middleware mounted without a path will be executed for every request to the app.</p>
<pre><code class="lang-js">// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})
</code></pre>
<p>Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.</p>
<pre><code class="lang-js">// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
})
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome');
})
</code></pre>
<p><code>path</code> can be a string representing a path, a path pattern, a regular expression to match paths, or an array of combinations of the aforementioned path objects.</p>
<div class="doc-box doc-notice">The middleware examples below are intentionally left overly simple to keep the examples lean and clutter-free.</div>
<table class="doctable" border="1">
<thead>
<tr>
<th> Type </th>
<th> Example </th>
</tr>
</thead>
<tbody>
<tr>
<td><strong> Path </strong></td>
<td>
<pre><code class="lang-js">// will match paths starting with /abcd
app.use('/abcd', function (req, res, next) {
next();
})</code></pre>
</tr>
<tr>
<td><strong> Path Pattern </strong></td>
<td>
<pre><code class="lang-js">// will match paths starting with /abcd and /abd
app.use('/abc?d', function (req, res, next) {
next();
})
// will match paths starting with /abcd, /abbcd, /abbbbbcd and so on
app.use('/ab+cd', function (req, res, next) {
next();
})
// will match paths starting with /abcd, /abxcd, /abFOOcd, /abbArcd and so on
app.use('/ab*cd', function (req, res, next) {
next();
})
// will match paths starting with /ad and /abcd
app.use('/a(bc)?d', function (req, res, next) {
next();
})</code></pre>
</td>
</tr>
<tr>
<td><strong> Regular Expression </strong></td>
<td>
<pre><code class="lang-js">// will match paths starting with /abc and /xyz
app.use(/\/abc|\/xyz/, function (req, res, next) {
next();
})</code></pre>
</td>
</tr>
<tr>
<td><strong> Array </strong></td>
<td>
<pre><code class="lang-js">// will match paths starting with /abcd, /xyza, /lmn, and /pqr
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
next();
})</code></pre>
</td>
</tr>
</tbody>
</table>
<p><code>function</code> can be a middleware function, a series of middleware functions, an array of middleware functions, or a combination of all of them. Since routers and apps implement the middleware interface, they can be used like any other middleware function.</p>
<table class="doctable" border="1">
<thead>
<tr>
<th>Usage</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong> Single Middleware </strong></td>
<td>
A middleware function can be defined and mounted locally.
<pre><code class="lang-js">app.use(function (req, res, next) {
next();
})
</code></pre>
A router is a valid middleware.
<pre><code class="lang-js">var router = express.Router();
router.get('/', function (req, res, next) {
next();
})
app.use(router);
</code></pre>
An Express app is a valid middleware.
<pre><code class="lang-js">var subApp = express();
subApp.get('/', function (req, res, next) {
next();
})
app.use(subApp);
</code></pre>
</tr>
<tr>
<td><strong>Series of Middleware</strong></td>
<td>
More than one middleware can be specified at a mount path.
<pre><code class="lang-js">var r1 = express.Router();
r1.get('/', function (req, res, next) {
next();
})
var r2 = express.Router();
r2.get('/', function (req, res, next) {
next();
})
app.use(r1, r2);
</code></pre>
</tr>
<tr>
<td><strong> Array </strong></td>
<td>
Clubbing middleware in arrays is a good way to logically group them. The mount path has to be specified, if an array of middleware is passed as the first or the only set of middleware.
<pre><code class="lang-js">var r1 = express.Router();
r1.get('/', function (req, res, next) {
next();
})
var r2 = express.Router();
r2.get('/', function (req, res, next) {
next();
})
app.use('/', [r1, r2]);
</code></pre>
</td>
</tr>
<tr>
<td><strong> Combination </strong></td>
<td>
All the above ways of mounting middleware can be combined.
<pre><code class="lang-js">function mw1(req, res, next) { next(); }
function mw2(req, res, next) { next(); }
var r1 = express.Router();
r1.get('/', function (req, res, next) { next(); });
var r2 = express.Router();
r2.get('/', function (req, res, next) { next(); });
var subApp = express();
subApp.get('/', function (req, res, next) { next(); });
app.use(mw1, [mw2, r1, r2], subApp);
</code></pre>
</td>
</tr>
</tbody>
</table>
<p>Following are some examples of using the <a href="#express.static">express.static</a> middleware in an Express app.</p>
<p>Serve static content for the app from the "public" directory in the application directory.</p>
<pre><code class="lang-js">// GET /style.css etc
app.use(express.static(__dirname + '/public'));
</code></pre>
<p>Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".</p>
<pre><code class="lang-js">// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
</code></pre>
<p>Disable logging for static content requests by loading the logger middleware after the static middleware.</p>
<pre><code class="lang-js">app.use(express.static(__dirname + '/public'));
app.use(logger());
</code></pre>
<p>Serve static files from multiple directories, but give precedence to "./public" over the others.</p>
<pre><code class="lang-js">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.engine">app.engine(ext, callback)</h3><p>Register the given template engine <code>callback</code> as <code>ext</code>.</p>
<p>By default, Express 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><code class="lang-js">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><code class="lang-js">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><code class="lang-js">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><em>Note</em></p>
<ul>
<li>Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on <code>app</code> will be triggered only by route parameters defined on <code>app</code> routes.</li>
<li>A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes.</li>
</ul>
<pre><code class="lang-js">app.param('id', function (req, res, next, id) {
console.log('CALLED ONLY ONCE');
next();
})
app.get('/user/:id', function (req, res, next) {
console.log('although this matches');
next();
});
app.get('/user/:id', function (req, res) {
console.log('and this matches too');
res.end();
});
</code></pre>
<p>The following snippet illustrates how the <code>callback</code>
is much like middleware, thus supporting async operations. However,
it provides the additional value of the parameter (here named as <code>id</code>), derived from the corresponding parameter in the <code>req.params</code> object.
An attempt to load the user is then performed, assigning <code>req.user</code>;
otherwise an error is passed to <code>next(err)</code>.</p>
<pre><code class="lang-js">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 can 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/expressjs/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. It is checking if the second argument is a regular
expression, returning the callback, which acts much like the "user" param example.</p>
<pre><code class="lang-js">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 (and
optionally parse them to provide capture groups):</p>
<pre><code class="lang-js">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.METHOD">app.METHOD(path, [callback...], callback)</h3><p>The <code>app.METHOD()</code> methods provide the routing functionality in Express, where <strong>METHOD</strong> is derived from
one of the HTTP or augmented methods, and lowercased. These methods look like <code>app.get()</code>, <code>app.post()</code>, <code>app.patch()</code>, and so on.</p>
<p>The following methods are supported by Express: <code>get</code>, <code>post</code>, <code>put</code>, <code>head</code>, <code>delete</code>, <code>options</code>, <code>trace</code>, <code>copy</code>, <code>lock</code>, <code>mkcol</code>, <code>move</code>, <code>purge</code>, <code>propfind</code>, <code>proppatch</code>, <code>unlock</code>, <code>report</code>, <code>mkactivity</code>, <code>checkout</code>, <code>merge</code>, <code>m-search</code>, <code>notify</code>, <code>subscribe</code>, <code>unsubscribe</code>, <code>patch</code>, <code>search</code>, and <code>connect</code>.</p>
<div class="doc-box doc-info">
To route methods which translate to invalid JavaScript variable names, use the bracket notation:
<code>app['m-search']('/', function () { ... })</code>
</div>
<p>Multiple callbacks may be given; all are treated
equally, and behave just like middleware. The only exception is 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 if there's no reason to proceed
with the current route.</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><code class="lang-js">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><code class="lang-js">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><code class="lang-js">app.get('/user/:id', user.load, function(){
// ...
})
</code></pre>
<p>If you have multiple common middleware for a route, you can use the route API with <code>all</code>.</p>
<pre><code class="lang-js">var middleware = [loadForum, loadThread];
app.route('/forum/:fid/thread/:tid')
.all(loadForum)
.all(loadThread)
.get(function() { //... });
.post(function() { //... });
</code></pre>
<p>Both middleware will be run for GET and POST requests.</p>
</section><section><h3 id="app.all">app.all(path, [callback...], callback)</h3><p>This method functions just like the <code>app.METHOD()</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><code class="lang-js">app.all('*', requireAuthentication, loadUser);
</code></pre>
<p>Or the equivalent:</p>
<pre><code class="lang-js">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><code class="lang-js">app.all('/api/*', requireAuthentication);
</code></pre>
</section><section><h3 id="app.route">app.route(path)</h3><p>Returns an instance of a single route, which can then be used to handle HTTP verbs with optional middleware. Using <code>app.route()</code> is a recommended approach for avoiding duplicate route names (and thus typo errors).</p>
<pre><code class="lang-js">var app = express();
app.route('/events')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function(req, res, next) {
res.json(...);
})
.post(function(req, res, next) {
// maybe add a new event...
})
</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><code class="lang-js">app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';
</code></pre>
<p>The <code>app.locals</code> object is a JavaScript <code>Object</code>. The
properties added to it will be exposed as local variables within the application.</p>
<pre><code class="lang-js">app.locals.title
// => 'My App'
app.locals.email
// => 'me@myapp.com'
</code></pre>
<p>By default, Express exposes only a single app-level local variable: <code>settings</code>.</p>
<pre><code class="lang-js">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><code class="lang-js">app.render('email', function(err, html){
// ...
});
app.render('email', { name: 'Tobi' }, function(err, html){
// ...
});
</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></a>.</p>
<pre><code class="lang-js">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><code class="lang-js">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 a convenience method for the following
(if you wish to use HTTPS or provide both, use the technique above):</p>
<pre><code class="lang-js">app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
</code></pre>
</section><section><h3 id="app.path">app.path()</h3><p>Returns the canonical path of the app.</p>
<pre><code class="lang-js">var app = express()
, blog = express()
, blogAdmin = express();
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'
</code></pre>
<p>The behavior of this method can become very complicated in complex cases of mounted apps, hence it is recommended to use <a href="#req.baseUrl">req.baseUrl</a> to get the canonical path of the app.</p>
</section><section><h3 id="app.mountpath">app.mountpath</h3><p>This property refers to the path pattern(s) on which a sub app was mounted.</p>
<pre><code class="lang-js">var admin = express();
admin.get('/', function (req, res) {
console.log(admin.mountpath); // /admin
res.send('Admin Homepage');
})
app.use('/admin', admin); // mount the sub app
</code></pre>
<p>It is similar to the <a href="#req.baseUrl">baseUrl</a> property of the <code>req</code> object, except <code>req.baseUrl</code> returns the matched URL path, instead of the matched pattern(s).</p>
<p>If a sub app is mounted on multiple path patterns, <code>app.mountpath</code> returns the list of patterns it is mounted on, as shown in the following example. </p>
<pre><code class="lang-js">var admin = express();
admin.get('/', function (req, res) {
console.log(admin.mountpath); // [ '/adm*n', '/manager' ]
res.send('Admin Homepage');
})
var secret = express();
secret.get('/', function (req, res) {
console.log(secret.mountpath); // /secr*t
res.send('Admin Secret');
});
admin.use('/secr*t', secret); // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin); // load the 'admin' router on '/adm*n' and '/manager', on the parent app
</code></pre>
</section><section><h3 id="app.onmount">app.on('mount', callback(parent))</h3><p>The <code>mount</code> event is fired on a sub app, when it is mounted on a parent app. The parent app is passed to the callback function.</p>
<pre><code class="lang-js">var admin = express();
admin.on('mount', function (parent) {
console.log('Admin Mounted');
console.log(parent); // refers to the parent app
});
admin.get('/', function (req, res) {
res.send('Admin Homepage');
});
app.use('/admin', admin);
</code></pre>
</section><h2>Request</h2><a id="request" class="h2"></a><section><h3 id="req.params">req.params</h3><p>This property is an object 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><code class="lang-js">// 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 <code>/file/*</code>:</p>
<pre><code class="lang-js">// 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><code class="lang-js">// 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>Contains the key-value pairs of data submitted in the request body. It is <code>undefined</code> by default, and is
populated with the use of a body-parsing middleware such as <a href="https://www.npmjs.org/package/body-parser">body-parser</a> and <a href="https://www.npmjs.org/package/multer">multer</a>.</p>
<p>The example below shows the use of body-parsing middleware to ppopulate <code>req.body</code>.</p>
<pre><code class="lang-js">var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
</code></pre>
</section><section><h3 id="req.param">req.param(name, [defaultValue])</h3><p>Return the value of param <code>name</code> when present.</p>
<pre><code class="lang-js">// ?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>Optionally, you can specify <code>defaultValue</code> to set a default value if the parameter is not found in any of the request objects.</p>
<div class="doc-box doc-warn">
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.
Body-parsing middleware must be loaded for <code>req.param()</code> to work predictably. Refer <a href="#req.body">req.body</a> for details.
</div>
</section><section><h3 id="req.route">req.route</h3><p>The currently matched <code>Route</code>.</p>
<pre><code class="lang-js">app.get('/user/:id?', function userIdHandler(req, res) {
console.log(req.route);
res.send('GET');
})
</code></pre>
<p>Example output from the previous snippet:</p>
<pre><code class="lang-js">{ path: '/user/:id?',
stack:
[ { handle: [Function: userIdHandler],
name: 'userIdHandler',
params: undefined,
path: undefined,
keys: [],
regexp: /^\/?$/i,
method: 'get' } ],
methods: { get: true } }
</code></pre>
</section><section><h3 id="req.cookies">req.cookies</h3><p>This object requires the <code>cookieParser()</code> middleware for use. It contains cookies sent by the user-agent. If no cookies are sent, it defaults to <code>{}</code>.</p>
<pre><code class="lang-js">// Cookie: name=tj
req.cookies.name
// => "tj"
</code></pre>
<p>Please refer to <a href="https://github.com/expressjs/cookie-parser">cookie-parser</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.signedCookies">req.signedCookies</h3><p>This object requires the <code>cookieParser(secret)</code> middleware for use. It contains 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 <code>req.cookie</code> values (which are easy to spoof). Note that signing a cookie does not make it "hidden" or encrypted; this simply prevents tampering (because the secret used to sign is private). If no signed cookies are sent, it defaults to <code>{}</code>.</p>
<pre><code class="lang-js">// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
req.signedCookies.user
// => "tobi"
</code></pre>
<p>Please refer to <a href="https://github.com/expressjs/cookie-parser">cookie-parser</a> for additional documentation or any issues and concerns.</p>
</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><code class="lang-js">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, or else <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><code class="lang-js">// 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>
<p>Please refer to <a href="https://github.com/expressjs/accepts">accepts</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.acceptsCharsets">req.acceptsCharsets(charset, ...)</h3><p>Check if the given <code>charset</code> are acceptable.</p>
<p>Please refer to <a href="https://github.com/expressjs/accepts">accepts</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.acceptsLanguages">req.acceptsLanguages(lang, ...)</h3><p>Check if the given <code>lang</code> are acceptable.</p>
<p>Please refer to <a href="https://github.com/expressjs/accepts">accepts</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.acceptsEncodings">req.acceptsEncodings(encoding, ...)</h3><p>Check if the given <code>encoding</code> are acceptable.</p>
<p>Please refer to <a href="https://github.com/expressjs/accepts">accepts</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.is">req.is(type)</h3><p>Check if the incoming request contains the "Content-Type" header field, and if it matches the give mime <code>type</code>.</p>
<pre><code class="lang-js">// 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>
<p>Please refer to <a href="https://github.com/expressjs/type-is">type-is</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.ip">req.ip</h3><p>Return the remote address (or, if "trust proxy" is enabled, the upstream address).</p>
<pre><code class="lang-js">req.ip
// => "127.0.0.1"
</code></pre>
</section><section><h3 id="req.ips">req.ips</h3><p>When "trust proxy" is <code>true</code>, parse the "X-Forwarded-For" ip address list and return an array. Otherwise, an empty array is returned.</p>
<p>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><code class="lang-js">// example.com/users?sort=desc
req.path
// => "/users"
</code></pre>
</section><section><h3 id="req.hostname">req.hostname</h3><p>Returns the hostname from the "Host" header field.</p>
<pre><code class="lang-js">// Host: "example.com:3000"
req.hostname
// => "example.com"
</code></pre>
</section><section><h3 id="req.fresh">req.fresh</h3><p>Check if the request is "fresh" (i.e. whether the Last-Modified and/or the ETag still match).</p>
<pre><code class="lang-js">req.fresh
// => true
</code></pre>
<p>Please refer to <a href="https://github.com/jshttp/fresh">fresh</a> for additional documentation or any issues and concerns.</p>
</section><section><h3 id="req.stale">req.stale</h3><p>Check if the request is "stale" (i.e. the Last-Modified and/or ETag headers do not match).</p>
<pre><code class="lang-js">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><code class="lang-js">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. If 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><code class="lang-js">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><code class="lang-js">'https' == req.protocol;
</code></pre>
</section><section><h3 id="req.subdomains">req.subdomains</h3><p>Return subdomains as an array.</p>
<pre><code class="lang-js">// 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><code class="lang-js">// GET /search?q=something
req.originalUrl
// => "/search?q=something"
</code></pre>
</section><section><h3 id="req.baseUrl">req.baseUrl</h3><p>This property refers to the URL path, on which a router instance was mounted.</p>
<pre><code class="lang-js">var greet = express.Router();
greet.get('/jp', function (req, res) {
console.log(req.baseUrl); // /greet
res.send('Konichiwa!');
});
app.use('/greet', greet); // load the router on '/greet'
</code></pre>
<p>Even if a path pattern or a set of path patterns were used to load the router, the matched string is returned as the <code>baseUrl</code>, instead of the pattern(s). In the following example, the <code>greet</code> router is loaded on two path patterns.</p>
<pre><code class="lang-js">app.use(['/gre+t', '/hel{2}o'], greet); // load the router on '/gre+t' and '/hel{2}o'
</code></pre>
<p>When the request is made to <code>/greet/jp</code>, <code>req.baseUrl</code> will be equal to "/greet"; and when the request is made to <code>/hello/jp</code>, it will be equal to "/hello".</p>
<p><code>req.baseUrl</code> is similar to the <a href="#app.mountpath">mountpath</a> property of the <code>app</code> object, except <code>app.mountpath</code> returns the matched path pattern(s).</p>
</section><h2>Response</h2><a id="response" class="h2"></a><section><h3 id="res.status">res.status(code)</h3><p>Chainable alias of node's <code>res.statusCode</code>. Use this method to set the HTTP status for the response.</p>
<pre><code class="lang-js">res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/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><code class="lang-js">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><code class="lang-js">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><code class="lang-js">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><code class="lang-js">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><code class="lang-js">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>cookieParser(secret)</code> to sign the value.</p>
<pre><code class="lang-js">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><code class="lang-js">res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });
</code></pre>
</section><section><h3 id="res.redirect">res.redirect([status], url)</h3><div class='doc-box doc-warn'>
<p>
Express passes the specified URL string as-is to the browser in the <code>Location</code> header, without any validation or manipulation, except in case of <code>back</code>.
</p>
<p>
Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the <code>Location</code> header; and redirect the user accordingly.
</p>
</div>
<p>Redirect to the given <code>url</code> with optional <code>status</code> code defaulting to 302 "Found".</p>
<pre><code class="lang-js">res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');
</code></pre>
<p>Redirects can be a fully qualified URI for redirecting to a different site:</p>
<pre><code class="lang-js">res.redirect('http://google.com');
</code></pre>
<p>Redirects can be relative to the root of the host name. 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><code class="lang-js">res.redirect('/admin');
</code></pre>
<p>Redirects can be relative to the current URL. A redirection of <code>post/new</code>, from <code>http://example.com/blog/admin/</code> (notice the trailing slash), would give you <code>http://example.com/blog/admin/post/new</code>.</p>
<pre><code class="lang-js">res.redirect('post/new');
</code></pre>
<p>Redirecting to <code>post/new</code> from <code>http://example.com/blog/admin</code> (no trailing slash), will take you to <code>http://example.com/blog/post/new</code>.</p>
<p>If you found the above behavior confusing, think of path segments as directories (have trailing slashes) and files, it will start to make sense.</p>
<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><code class="lang-js">res.redirect('..');
</code></pre>
<p>A <code>back</code> redirection will redirect the request back to the Referer (or Referrer), defaulting to <code>/</code> when missing.</p>
<pre><code class="lang-js">res.redirect('back');
</code></pre>
</section><section><h3 id="res.location">res.location</h3><p>Set the location header.</p>
<pre><code class="lang-js">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><code class="lang-js">res.location('admin')
</code></pre>
</section><section><h3 id="res.send">res.send([body])</h3><p>Send a response.</p>
<pre><code class="lang-js">res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
</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 <strong>HEAD</strong> 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><code class="lang-js">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><code class="lang-js">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><code class="lang-js">res.send({ user: 'tobi' });
res.send([1,2,3]);
</code></pre>
</section><section><h3 id="res.json">res.json([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, such as null, undefined, etc. (although these are technically not valid JSON).</p>
<pre><code class="lang-js">res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
</code></pre>
</section><section><h3 id="res.jsonp">res.jsonp([body])</h3><p>Send a JSON response with JSONP support. This method is identical to <code>res.json()</code>, except that it opts-in to JSONP callback support.</p>
<pre><code class="lang-js">res.jsonp(null)
// => null
res.jsonp({ user: 'tobi' })
// => { "user": "tobi" }
res.status(500).jsonp({ 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><code class="lang-js">// ?callback=foo
res.jsonp({ user: 'tobi' })
// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb');
// ?cb=foo
res.status(500).jsonp({ 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><code class="lang-js">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 Accept HTTP header on the request object, when present. It uses <a href="#req.accepts">req.accepts()</a> to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 "Not Acceptable", or invokes the <code>default</code> callback.</p>
<p>The Content-Type response header 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>