forked from expressjs/expressjs.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.html
More file actions
1617 lines (1492 loc) · 92.9 KB
/
Copy pathapi.html
File metadata and controls
1617 lines (1492 loc) · 92.9 KB
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/routing.html">Routing</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><li><a href="/guide/error-handling.html">Error handling</a></li><li><a href="/guide/debugging.html">Debugging</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/database-integration.html">Database integration</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="#app.express">express()</a></li><li><em>Properties</em></li><li><a href="#app.locals">app.locals</a></li><li><a href="#app.mountpath">app.mountpath</a></li><li><em>Events</em></li><li><a href="#app.onmount">mount</a></li><li><em>Methods</em></li><li><a href="#app.all">app.all()</a></li><li><a href="#app.delete.method">app.delete()</a></li><li><a href="#app.disable">app.disable()</a></li><li><a href="#app.disabled">app.disabled()</a></li><li><a href="#app.enable">app.enable()</a></li><li><a href="#app.enabled">app.enabled()</a></li><li><a href="#app.engine">app.engine()</a></li><li><a href="#app.get">app.get()</a></li><li><a href="#app.get.method">app.get()</a></li><li><a href="#app.listen">app.listen()</a></li><li><a href="#app.METHOD">app.METHOD()</a></li><li><a href="#app.param">app.param()</a></li><li><a href="#app.path">app.path()</a></li><li><a href="#app.post.method">app.post()</a></li><li><a href="#app.put.method">app.put()</a></li><li><a href="#app.render">app.render()</a></li><li><a href="#app.route">app.route()</a></li><li><a href="#app.set">app.set()</a></li><li><a href="#app.use">app.use()</a></li></ul></li><li id="req-api"><a href="#request">Request</a><ul id="req-menu"><li><em>Properties</em></li><li><a href="#req.baseUrl">req.baseUrl</a></li><li><a href="#req.body">req.body</a></li><li><a href="#req.cookies">req.cookies</a></li><li><a href="#req.fresh">req.fresh</a></li><li><a href="#req.hostname">req.hostname</a></li><li><a href="#req.ip">req.ip</a></li><li><a href="#req.ips">req.ips</a></li><li><a href="#req.originalUrl">req.originalUrl</a></li><li><a href="#req.params">req.params</a></li><li><a href="#req.path">req.path</a></li><li><a href="#req.protocol">req.protocol</a></li><li><a href="#req.query">req.query</a></li><li><a href="#req.route">req.route</a></li><li><a href="#req.secure">req.secure</a></li><li><a href="#req.signedCookies">req.signedCookies</a></li><li><a href="#req.stale">req.stale</a></li><li><a href="#req.subdomains">req.subdomains</a></li><li><a href="#req.xhr">req.xhr</a></li><li><em>Methods</em></li><li><a href="#req.accepts">req.accepts()</a></li><li><a href="#req.acceptsCharsets">req.acceptsCharsets()</a></li><li><a href="#req.acceptsEncodings">req.acceptsEncodings()</a></li><li><a href="#req.acceptsLanguages">req.acceptsLanguages()</a></li><li><a href="#req.get">req.get()</a></li><li><a href="#req.is">req.is()</a></li><li><a href="#req.param">req.param()</a></li></ul></li><li id="res-api"><a href="#response">Response</a><ul id="res-menu"><li><em>Properties</em></li><li><a href="#res.headersSent">res.headersSent</a></li><li><a href="#res.locals">res.locals</a></li><li><em>Methods</em></li><li><a href="#res.append">res.append()</a></li><li><a href="#res.attachment">res.attachment()</a></li><li><a href="#res.cookie">res.cookie()</a></li><li><a href="#res.clearCookie">res.clearCookie()</a></li><li><a href="#res.download">res.download()</a></li><li><a href="#res.end">res.end()</a></li><li><a href="#res.format">res.format()</a></li><li><a href="#res.get">res.get()</a></li><li><a href="#res.json">res.json()</a></li><li><a href="#res.jsonp">res.jsonp()</a></li><li><a href="#res.links">res.links()</a></li><li><a href="#res.location">res.location()</a></li><li><a href="#res.redirect">res.redirect()</a></li><li><a href="#res.render">res.render()</a></li><li><a href="#res.send">res.send()</a></li><li><a href="#res.sendFile">res.sendFile()</a></li><li><a href="#res.sendStatus">res.sendStatus()</a></li><li><a href="#res.set">res.set()</a></li><li><a href="#res.status">res.status()</a></li><li><a href="#res.type">res.type()</a></li><li><a href="#res.vary">res.vary()</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><em>Methods</em></li><li><a href="#router.all">router.all()</a></li><li><a href="#router.METHOD">router.METHOD()</a></li><li><a href="#router.param">router.param()</a></li><li><a href="#router.route">router.route()</a></li><li><a href="#router.use">router.use()</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="app.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><h3 id="app.properties">Properties</h3><section><h3 id="app.locals">app.locals</h3><p>The <code>app.locals</code> object is a JavaScript object, and its
properties are 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>Once set, the value of <code>app.locals</code> properties persist throughout the life of the application,
in contrast with <a href="#res.locals">res.locals</a> properties that
are valid only for the lifetime of the request.</p>
<p>You can accesss local variables in templates rendered within the application.
This is useful for providing helper functions to templates, as well as app-level data.
Note, however, that you cannot access local variables in middleware.</p>
<pre><code class="lang-js">app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';
</code></pre>
</section><section><h3 id="app.mountpath">app.mountpath</h3><p>The <code>app.mountpath</code> property is the path pattern(s) on which a sub app was mounted.</p>
<div class="doc-box doc-info">
A sub app is an instance <code>express</code> which may be used for handling the request to a route.
</div>
<pre><code class="lang-js">var express = required('express');
var app = express(); // the main app
var admin = express(); // the sub app
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><h3 id="app.events">Events</h3><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><h3 id="app.methods">Methods</h3><section><h3 id="app.all">app.all(path, callback [, callback ...])</h3><p>This method is like the standard <a href="#app.METHOD">app.METHOD()</a> methods,
except it matches <em>all</em> HTTP verbs. </p>
<p>It's useful for mapping "global" logic for specific path prefixes or arbitrary matches.
For example, if you put the following at the top of all other
route definitions, it requires that all routes from that point on
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 call <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 example is white-listed "global" functionality.
The example is much like before, however it only restricts paths that start with
"/api":</p>
<pre><code class="lang-js">app.all('/api/*', requireAuthentication);
</code></pre>
</section><section><h3 id="app.delete.method">app.delete(path, callback [, callback ...])</h3><p>Route HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the <a href="/guide/routing.html">routing guide</a>.</p>
<p>You can provide multiple callback functions that behave just like middleware. The only exception is that these callbacks may invoke <code>next('route')</code> to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.</p>
<pre><code class="lang-js">app.delete('/', function (req, res) {
res.send('DELETE request to homepage');
});
</code></pre>
</section><section><h3 id="app.disable">app.disable(name)</h3><p>Set Boolean setting <code>name</code> to <code>false</code>, where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>.
Calling <code>app.set('foo', false)</code> for a Boolean property is the same as calling <code>app.disable('foo')</code>.</p>
<p>For example:</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 the Boolean setting <code>name</code> is disabled (<code>false</code>), where <code>name</code> is one of the properties from
the <a href="#app.settings.table">app settings table</a>.</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.enable">app.enable(name)</h3><p>Set Boolean setting <code>name</code> to <code>true</code>, where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>.
Calling <code>app.set('foo', true)</code> for a Boolean property is the same as calling <code>app.enable('foo')</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, where <code>name</code> is one of the properties from the <a href="#app.settings.table">app settings table</a>.</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.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 invokes the following internally,
and caches 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>Use this method 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.</p>
<p>For example, to map 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 don't need to do anything.</p>
<p>Some template engines do not follow this convention. The
<a href="https://github.com/tj/consolidate.js">consolidate.js</a> library maps Node template engines to follow this convention,
so they work seemlessly with 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.get">app.get(name)</h3><p>Get the value of <code>name</code> app setting, where <code>name</code> is one of strings in the <a href="#app.settings.table">app settings table</a>. For example:</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.get.method">app.get(path, callback [, callback ...])</h3><p>Route HTTP GET requests to the specified path with the specified callback functions. For more information, see the <a href="/guide/routing.html">routing guide</a>.</p>
<p>You can provide multiple callback functions that behave just like middleware. The only exception is that these callbacks may invoke <code>next('route')</code> to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.</p>
<pre><code class="lang-js">app.get('/', function (req, res) {
res.send('GET request to homepage');
});
</code></pre>
</section><section><h3 id="app.listen">app.listen(port, [hostname], [backlog], [callback])</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 enables you to provide both HTTP and HTTPS versions of
your app with the same code base 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 (for HTTP only):</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.METHOD">app.METHOD(path, callback [, callback ...])</h3><p>Route an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. The corresponding routing methods are then <code>app.get()</code>, <code>app.post()</code>, <code>app.put()</code>, and so on. For more information, see the <a href="/guide/routing.html">routing guide</a>.</p>
<p>Express supports the following routing methods corresponding to HTTP methods: <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. For example,
<code>app['m-search']('/', function ...</code>.
</div>
<p>You can provide multiple callback functions that behave just like middleware. The only exception is that these callbacks may invoke <code>next('route')</code> to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.</p>
<div class="doc-box doc-info">
The API documentation explicitly includes only the most popular HTTP methods <code>app.get()</code>, <code>app.post()</code>, <code>app.put()</code>, and <code>app.delete()</code> to provide a quick sense of how things work. Other methods like <code>app.lock()</code>, <code>app.subscribe()</code>, and so on, work in exactly the same way.
</div>
<p>There is a special routing method, <code>app.all()</code>, which is not derived from any HTTP method. It is used for loading middleware at a path for all request methods.</p>
<p>In the following example, the handler will be executed for requests to "/secret" whether using GET, POST, PUT, DELETE, or any other HTTP request method.</p>
<pre><code class="lang-js">app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
</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>
<div class="doc-box doc-warn"><code>app.param(callback)</code> is deprecated as of v4.11.0.</div>
<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([0-9]+)', function(req, res){
res.send('user ' + req.params.id);
});
app.param('range', /^(\w+)\.\.(\w+)?$/);
app.get('/range/:range(\\w+\\.\\.\\w+)', function(req, res){
var range = req.params.range.split('..');
res.send('from ' + range[0] + ' to ' + range[1]);
});
</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.post.method">app.post(path, callback [, callback ...])</h3><p>Route HTTP POST requests to the specified path with the specified callback functions. For more information, see the <a href="/guide/routing.html">routing guide</a>.</p>
<p>You can provide multiple callback functions that behave just like middleware. The only exception is that these callbacks may invoke <code>next('route')</code> to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.</p>
<pre><code class="lang-js">app.post('/', function (req, res) {
res.send('POST request to homepage');
});
</code></pre>
</section><section><h3 id="app.put.method">app.put(path, callback [, callback ...])</h3><p>Route HTTP PUT requests to the specified path with the specified callback functions. For more information, see the <a href="/guide/routing.html">routing guide</a>.</p>
<p>You can provide multiple callback functions that behave just like middleware. The only exception is that these callbacks may invoke <code>next('route')</code> to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.</p>
<pre><code class="lang-js">app.put('/', function (req, res) {
res.send('PUT request to homepage');
});
</code></pre>
</section><section><h3 id="app.render">app.render(view, [locals], callback)</h3><p>Return the rendered HTML of a view via the <code>callback</code> function. It accepts an optional object of local variables for the view. It is like <a href="#res.render">res.render()</a>, except it cannot send the rendered view to the client on its own.</p>
<div class="doc-box doc-info">
Think of <code>app.render()</code> as a utility function for generating rendered view strings. Internally <code>res.render()</code> uses <code>app.render()</code> to render views.
</div>
<div class="doc-box doc-notice">
The local variable <code>cache</code> is reserved for enabling view cache. Set it to <code>true</code>, if you want to cache view during development; view caching is enabled in production by default.
</div>
<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.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.set">app.set(name, value)</h3><p>Assign setting <code>name</code> to <code>value</code>, where <code>name</code> is one of the properties from
the <a href="#app.settings.table">app settings table</a>. </p>
<p>Calling <code>app.set('foo', true)</code> for a Boolean property is the same as calling
<code>app.enable('foo')</code>. Similarly, calling <code>app.set('foo', false)</code> for a Boolean
property is the same as calling <code>app.disable('foo')</code>.</p>
<p>Retrieve the value of a setting with <a href="#app.get"><code>app.get()</code></a>.</p>
<pre><code class="lang-js">app.set('title', 'My Site');
app.get('title'); // "My Site"
</code></pre>
<h4 id="app.settings.table">Application Settings</h4><p>If <code>name</code> is one of the application settings, it affects the behavior of the application. The following table lists application settings.</p>
<table class="doctable" border="1">
<thead><tr><th id="app-settings-property">Property</th><th>Type</th><th>Value</th><th>Default</th></tr></thead>
<tbody>
<tr>
<td><code>case sensitive routing</code></td>
<td>Boolean</td>
<td>Enable case sensitivity.</td>
<td>Disabled. Treats "/Foo" and "/foo" as the same.</td>
</tr>
<tr>
<td><code>env</code></td>
<td>String</td>
<td>Environment mode.</td>
<td><code>process.env.NODE_ENV</code> (<code>NODE_ENV</code> environment variable) or "development".</td>
</tr>
<tr>
<td><code>etag</code></td>
<td>Varied</td>
<td>
<p>Set the ETag response header. For possible values, see the <a href="#etag.options.table"><code>etag</code> options table</a>.</p>
<p><a href="http://en.wikipedia.org/wiki/HTTP_ETag">More about the HTTP ETag header</a>.</p>
</td>
<td></td>
</tr>
<tr>
<td><code>jsonp callback name</code></td>
<td>String</td>
<td>Specifies the default JSONP callback name.</td>
<td><code>?callback=</code></td>
</tr>
<tr>
<td><code>json replacer</code></td>
<td>String</td>
<td>JSON replacer callback.</td>
<td><code>null</code></td>
</tr>
<tr>
<td><code>json spaces</code></td>
<td>Number</td>
<td>When set, sends prettified JSON string indented with the specified amount of spaces.</td>
<td>Disabled.</td>
</tr>
<tr>
<td><code>query parser</code></td>
<td>String</td>
<td>The query parser to use, either "simple" or "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>.</td>
<td>"extended"</td>
</tr>
<tr>
<td><code>strict routing</code></td>
<td>Boolean</td>
<td>Enable strict routing.</td>
<td>Disabled. Treats "/foo" and "/foo/" as the same by the router.</td>
</tr>
<tr>
<td><code>subdomain offset</code></td>
<td>Number</td>
<td>The number of dot-separated parts of the host to remove to access subdomain.</td>
<td>2</td>
</tr>
<tr>
<td><code>trust proxy</code></td>
<td>Varied</td>
<td>
<p>
Indicates the app is behind a front-facing proxy, and to use the <code>X-Forwarded-*</code> headers to determine the connection and the IP address of the client. NOTE: <code>X-Forwarded-*</code> headers are easily spoofed and the detected IP addresses are unreliable.<br> </p>
<p>
<code>trust proxy</code> is disabled by default. When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The <code>req.ips</code> property, then, contains an array of IP addresses the client is connected through. To enable it, use the values described in the <a href="#trust.proxy.options.table"><code>trust proxy</code> options table</a>.<br> </p>
<p>
The <code>trust proxy</code> setting is implemented using the <a href="https://www.npmjs.org/package/proxy-addr">proxy-addr</a> package. For more information, see its documentation.
</p>
</td>
<td>Disabled.</td>
</tr>
<tr>
<td><code>views</code></td>
<td>String or Array</td>
<td>A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.</td>
<td><code>"process.cwd() + '/views'"</code></td>
</tr>
<tr>
<td><code>view cache</code></td>
<td>Boolean</td>
<td>Enables view template compilation caching.</td>
<td><code>true</code> in production.</td>
</tr>
<tr>
<td><code>view engine</code></td>
<td>String</td>
<td>The default engine extension to use when omitted.</td>
<td></td>
</tr>
<tr>
<td><code>x-powered-by</code></td>
<td>Boolean</td>
<td>Enables the "X-Powered-By: Express" HTTP header.</td>
<td><code>true</code></td>
</tr>
</tbody>
</table>
<h5 id="trust.proxy.options.table">Options for <code>trust proxy</code> setting</h5>
<table class="doctable" border="1">
<thead><tr><th>Type</th><th>Value</th></tr></thead>
<tbody>
<tr>
<td><strong> Boolean </strong></td>
<td>
<p>
If <code>true</code>, the client's IP address is understood as the left-most entry in the <code>X-Forwarded-*</code> header.<br> </p>
<p>
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.
</p>
</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>
Set IP addresses in any of 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>
<h5 id="etag.options.table">Options for <code>etag</code> setting</h5>
<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 weak 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>
</section><section><h3 id="app.use">app.use([path,] function [, function...])</h3><p>Mount the <a href="/guide/using-middleware.html">middleware</a> <code>function</code>(s) at the <code>path</code>. If <code>path</code> is not specified, it defaults to "/".</p>
<div class="doc-box doc-notice">
A route will match any path, which follows its path immediately with a "<code>/</code>". For example: <code>app.use('/apple', ...)</code> will match <b>/apple</b>, <b>/apple/images</b>, <b>/apple/images/news</b>, and so on.<br></div>
<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 in the below are simple examples.</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, you can use them as you would 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>You can define and mount a middleware function locally.
<pre><code class="lang-js">app.use(function (req, res, next) {
next();
})
</code></pre>
A router is 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 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>
You can specify more than one middleware function at the same 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>
Use an array to group middleware logically.
If you pass an array of middleware as the first or only middleware parameters, then you <em>must</em> specify the 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>
</td>
</tr>
<tr>
<td><strong> Combination </strong></td>
<td>
You can combine all the above ways of mounting middleware.
<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="/guide/using-middleware.html#middleware.built-in">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><h2>Request</h2><a id="request" class="h2"></a><h3 id="req.properties">Properties</h3><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><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 populate <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.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.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.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.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.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.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.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.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.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.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.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.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.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.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.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><h3 id="req.methods">Methods</h3><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.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.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.get">req.get(field)</h3><p>Get the case-insensitive request header <code>field</code>. The <code>Referrer</code> and <code>Referer</code> 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.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.param">req.param(name, [defaultValue])</h3><div class="doc-box doc-warn">Deprecated. Use either <code>req.params</code>, <code>req.body</code> or <code>req.query</code>, as applicable.</div>
<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><h2>Response</h2><a id="response" class="h2"></a><h3 id="res.properties">Properties</h3><section><h3 id="res.headersSent">res.headersSent</h3><p>Property indicating if HTTP headers has been sent for the response.</p>
<pre><code class="lang-js">app.get('/', function (req, res) {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
})
</code></pre>
</section><section><h3 id="res.locals">res.locals</h3><p>Response local variables are scoped to the request, and therefore 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 etc.</p>
<pre><code class="lang-js">app.use(function(req, res, next){
res.locals.user = req.user;
res.locals.authenticated = ! req.user.anonymous;
next();
});
</code></pre>
</section><h3 id="res.methods">Methods</h3><section><h3 id="res.append">res.append(field, [value])</h3><div class="doc-box doc-info"><code>res.append()</code> is supported from Express v4.11.0 onwards</div>
<p>Append additional value <code>value</code> to an existing header named <code>field</code>; or create the header with the value <code>value</code>, if the header is not already set. <code>value</code> can be a string or an array of values to be appended.</p>
<p>Note that, calling <code>res.set()</code> after <code>res.append()</code> will reset the previously set header value.</p>
<pre><code class="lang-js">res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
res.append('Warning', '199 Miscellaneous warning');
</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><code class="lang-js">res.attachment();
// Content-Disposition: attachment
res.attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"