-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode_express.html
More file actions
613 lines (584 loc) · 36.1 KB
/
node_express.html
File metadata and controls
613 lines (584 loc) · 36.1 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
<!doctype html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node Web App — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbo-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/highlight.css" data-turbo-track="reload">
<link rel="icon" href="images/backend-development.svg" sizes="any">
<script src="javascripts/@hotwired--turbo.js" data-turbo-track="reload"></script>
<script src="javascripts/clipboard.js" data-turbo-track="reload"></script>
<script src="javascripts/guides.js" data-turbo-track="reload"></script>
<meta property="og:title" content="Node Web App — Ruby on Rails Guides" />
<meta name="description" content="Node Web AppAfter working through this guide you should be able to set up and program a web project with express understand the role of connect middleware build a REST API with node.js" />
<meta property="og:description" content="Node Web AppAfter working through this guide you should be able to set up and program a web project with express understand the role of connect middleware build a REST API with node.js" />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Textbook Backend Developemnt" />
<meta property="og:image" content="images/backend-development.svg" />
<meta property="og:type" content="website" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet">
<meta name="theme-color" content="#2e56e9">
</head>
<body class="guide">
<header id="page_header">
<div class="wrapper clearfix">
<nav id="feature_nav">
<div class="header-logo">
<a href="/">Backend Development</a>
</div>
<ul class="nav">
<li><a class="nav-item" id="home_nav" href="/">Home</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Index</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="guides-section-container">
<div class="guides-section">
<dt>Ruby on Rails</dt>
<dd><a href="ruby_commandline.html">Ruby Commandline</a></dd>
<dd><a href="rails_database_and_model.html">Models and ActiveRecord</a></dd>
<dd><a href="rails_db.html">Database and Migrations</a></dd>
<dd><a href="rails_associations_and_validations.html">Associations and Validations</a></dd>
<dd><a href="rails_view_and_controller.html">Routing, View and Controller</a></dd>
<dd><a href="rails_authentication.html">Simple Authentication</a></dd>
<dd><a href="assets_and_import_map.html">The Asset Pipeline and Importmaps</a></dd>
<dd><a href="testing.html">Getting started with Testing</a></dd>
<dd><a href="refactoring_rails.html">Refactoring Rails</a></dd>
<dd><a href="deploy-to-paas.html">Deploy to PAAS</a></dd>
<dd><a href="rails_gems.html">Ruby Gems for your Rails Project</a></dd>
<dd><a href="deploying_rails.html">Deploying Rails</a></dd>
</div>
<div class="guides-section">
<dt>Ruby on Rails - Advanced Topics</dt>
<dd><a href="deploy-to-paas.html">Deploy to PAAS</a></dd>
<dd><a href="rest-api.html">REST API</a></dd>
<dd><a href="graphql-api.html">GraphQL API</a></dd>
<dd><a href="rails_websockets.html">Websocket in Rails</a></dd>
<dd><a href="jobs_and_tasks.html">Jobs and Tasks in Rails</a></dd>
<dd><a href="rails_security.html">Rails Security</a></dd>
</div>
<div class="guides-section">
<dt>Overarching Concerns</dt>
<dd><a href="issue.html">Issue Lifecycle</a></dd>
<dd><a href="security.html">Security</a></dd>
<dd><a href="adv_authentication.html">Advanced Authentication</a></dd>
<dd><a href="caching.html">Caching</a></dd>
<dd><a href="advanced_testing.html">Advanced Testing</a></dd>
<dd><a href="internationalization.html">Internationalization (I18n)</a></dd>
<dd><a href="git_rebasing.html">Git Rebasing</a></dd>
</div>
<div class="guides-section">
<dt>Nodes.js</dt>
<dd><a href="node_vs_rails.html">Node vs. Rails</a></dd>
<dd><a href="node_basics.html">Node Basics</a></dd>
<dd><a href="node_websockets.html">Node Websockets</a></dd>
<dd><a href="node_express.html">Node Web App</a></dd>
<dd><a href="node_cluster.html">Scaling Node</a></dd>
</div>
<div class="guides-section">
<dt>Next.js</dt>
<dd><a href="nextjs.html">Next.js</a></dd>
</div>
</dl>
</div>
</li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Index</option>
<optgroup label="Ruby on Rails">
<option value="ruby_commandline.html">Ruby Commandline</option>
<option value="rails_database_and_model.html">Models and ActiveRecord</option>
<option value="rails_db.html">Database and Migrations</option>
<option value="rails_associations_and_validations.html">Associations and Validations</option>
<option value="rails_view_and_controller.html">Routing, View and Controller</option>
<option value="rails_authentication.html">Simple Authentication</option>
<option value="assets_and_import_map.html">The Asset Pipeline and Importmaps</option>
<option value="testing.html">Getting started with Testing</option>
<option value="refactoring_rails.html">Refactoring Rails</option>
<option value="deploy-to-paas.html">Deploy to PAAS</option>
<option value="rails_gems.html">Ruby Gems for your Rails Project</option>
<option value="deploying_rails.html">Deploying Rails</option>
</optgroup>
<optgroup label="Ruby on Rails - Advanced Topics">
<option value="deploy-to-paas.html">Deploy to PAAS</option>
<option value="rest-api.html">REST API</option>
<option value="graphql-api.html">GraphQL API</option>
<option value="rails_websockets.html">Websocket in Rails</option>
<option value="jobs_and_tasks.html">Jobs and Tasks in Rails</option>
<option value="rails_security.html">Rails Security</option>
</optgroup>
<optgroup label="Overarching Concerns">
<option value="issue.html">Issue Lifecycle</option>
<option value="security.html">Security</option>
<option value="adv_authentication.html">Advanced Authentication</option>
<option value="caching.html">Caching</option>
<option value="advanced_testing.html">Advanced Testing</option>
<option value="internationalization.html">Internationalization (I18n)</option>
<option value="git_rebasing.html">Git Rebasing</option>
</optgroup>
<optgroup label="Nodes.js">
<option value="node_vs_rails.html">Node vs. Rails</option>
<option value="node_basics.html">Node Basics</option>
<option value="node_websockets.html">Node Websockets</option>
<option value="node_express.html">Node Web App</option>
<option value="node_cluster.html">Scaling Node</option>
</optgroup>
<optgroup label="Next.js">
<option value="nextjs.html">Next.js</option>
</optgroup>
</select>
</li>
</ul>
</nav>
</div>
</header>
<hr class="hide" />
<section id="feature">
<div class="wrapper">
<h1>Node Web App</h1><p>After working through this guide you should be able to</p>
<ul>
<li>set up and program a web project with express</li>
<li>understand the role of connect middleware</li>
<li>build a REST API with node.js</li>
</ul>
<nav id="subCol">
<h3 class="chapter">
<picture>
<!-- Using the `source` HTML tag to set the dark theme image -->
<source
srcset="images/icon_book-close-bookmark-1-wht.svg"
media="(prefers-color-scheme: dark)"
/>
<img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" />
</picture>
Chapters
</h3>
<ol class="chapters">
<li><a href="#connect">Connect</a></li>
<li><a href="#write-you-own-middleware">Write you own middleware</a></li>
<li><a href="#express">Express</a>
<ul>
<li><a href="#setup">Setup</a></li>
</ul></li>
<li><a href="#building-an-api">Building an API</a>
<ul>
<li><a href="#serving-static-assets">Serving static assets</a></li>
<li><a href="#routes">Routes</a></li>
<li><a href="#serving-json">Serving JSON</a></li>
<li><a href="#more-routing">More Routing</a></li>
<li><a href="#set-up-cors-for-a-frontend">Set up CORS for a frontend</a></li>
</ul></li>
<li><a href="#server-rendered-html">Server rendered HTML</a>
<ul>
<li><a href="#views-with-jade">Views with JADE</a></li>
<li><a href="#working-with-data">Working with data</a></li>
</ul></li>
<li><a href="#see-also">See Also</a></li>
</ol>
</nav>
<hr>
</div>
</section>
<main id="container">
<div class="wrapper">
<div id="mainCol">
<div class='slide'>
<p>We have already seen a very basic web server in node.js:</p><div class="interstitial code">
<pre><code class="highlight plaintext">import * as http from 'http';
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello Web\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
</code></pre>
<button class="clipboard-button" data-clipboard-text="import * as http from 'http';
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello Web\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
">Copy</button>
</div>
<p>Not let's look at connect and express, two libraries
that make web projects easier.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-0' href='slides_node_express.html#/0'>◻</a></p>
<h2 id="connect"><a class="anchorlink" href="#connect"><span>1</span> Connect</a></h2><p>Connect is a middleware framework for node
Built on top of node’s Http Server</p><div class="interstitial code">
<pre><code class="highlight plaintext">var connect = require('connect');
var app = connect()
.use(function(req, res){
res.end('hello world\n');
})
.listen(3000);
console.log("server listening on port 3000");
</code></pre>
<button class="clipboard-button" data-clipboard-text="var connect = require('connect');
var app = connect()
.use(function(req, res){
res.end('hello world\n');
})
.listen(3000);
console.log("server listening on port 3000");
">Copy</button>
</div>
<p><img src="images/connect.svg" alt=""></p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-1' href='slides_node_express.html#/1'>◻</a></p>
<h2 id="write-you-own-middleware"><a class="anchorlink" href="#write-you-own-middleware"><span>2</span> Write you own middleware</a></h2><p>Write a function that recieves the arguments
request, response and next. This function can
read from and also manipulate request and response.
After it is done, it must call <code>next()</code> to hand
over control to the next middleware.</p><div class="interstitial code">
<pre><code class="highlight plaintext">var connect = require('connect');
var app = connect()
// my middleware
.use(function(request, response, next) {
console.log(`Request for ${request.url} with method ${request.method}`);
next();
})
// handle all requests
.use(function onRequest(request, response) {
response.end('Hello from connect with middleware!');
})
.listen(3000);
console.log("Server listening on port 3000");
</code></pre>
<button class="clipboard-button" data-clipboard-text="var connect = require('connect');
var app = connect()
// my middleware
.use(function(request, response, next) {
console.log(`Request for ${request.url} with method ${request.method}`);
next();
})
// handle all requests
.use(function onRequest(request, response) {
response.end('Hello from connect with middleware!');
})
.listen(3000);
console.log("Server listening on port 3000");
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-2' href='slides_node_express.html#/2'>◻</a></p>
<h2 id="express"><a class="anchorlink" href="#express"><span>3</span> Express</a></h2><p>Express is a minimalist framework for building
APIs and server rendered web apps with node.js.
It offers:</p>
<ul>
<li>a project generator</li>
<li>request / response enhancements</li>
<li>routing</li>
<li>view support</li>
<li>HTML helpers</li>
<li>content negotiation</li>
</ul>
<p>it is built on top of <code>connect</code>.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-3' href='slides_node_express.html#/3'>◻</a></p>
<h3 id="setup"><a class="anchorlink" href="#setup"><span>3.1</span> Setup</a></h3><div class="interstitial code">
<pre><code class="highlight plaintext">npx express-generator --git projectname
</code></pre>
<button class="clipboard-button" data-clipboard-text="npx express-generator --git projectname
">Copy</button>
</div>
<p>Creates your project with all the necessary packages.</p><div class="interstitial code">
<pre><code class="highlight plaintext">cd projectname
npm install
</code></pre>
<button class="clipboard-button" data-clipboard-text="cd projectname
npm install
">Copy</button>
</div>
<p>Installs all dependencies to your project</p><div class="interstitial code">
<pre><code class="highlight plaintext">DEBUG=node-express:* npm start
</code></pre>
<button class="clipboard-button" data-clipboard-text="DEBUG=node-express:* npm start
">Copy</button>
</div>
<p>has your project up and running</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-4' href='slides_node_express.html#/4'>◻</a></p>
<h2 id="building-an-api"><a class="anchorlink" href="#building-an-api"><span>4</span> Building an API</a></h2><p>If you want to use express for an API only, you can
set it up without views:</p><div class="interstitial code">
<pre><code class="highlight plaintext">npx express-generator --no-view --git restproject
</code></pre>
<button class="clipboard-button" data-clipboard-text="npx express-generator --no-view --git restproject
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-5' href='slides_node_express.html#/5'>◻</a></p>
<h3 id="serving-static-assets"><a class="anchorlink" href="#serving-static-assets"><span>4.1</span> Serving static assets</a></h3><p>The generator created a folder public/ with some files
and subfolders:</p><div class="interstitial code">
<pre><code class="highlight plaintext"> create : restproject/
create : restproject/public/
create : restproject/public/javascripts/
create : restproject/public/images/
create : restproject/public/stylesheets/
create : restproject/public/stylesheets/style.css
create : restproject/public/index.html
</code></pre>
<button class="clipboard-button" data-clipboard-text=" create : restproject/
create : restproject/public/
create : restproject/public/javascripts/
create : restproject/public/images/
create : restproject/public/stylesheets/
create : restproject/public/stylesheets/style.css
create : restproject/public/index.html
">Copy</button>
</div>
<p>the <code>express.static</code> middleware is used to
serve these files. It will look for <code>index.html</code> if
a folder is requested.</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="nx">app</span><span class="p">.</span><span class="nf">use</span><span class="p">(</span><span class="nx">express</span><span class="p">.</span><span class="nf">static</span><span class="p">(</span><span class="nx">path</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="nx">__dirname</span><span class="p">,</span> <span class="dl">'</span><span class="s1">public</span><span class="dl">'</span><span class="p">)));</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="app.use(express.static(path.join(__dirname, 'public')));
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-6' href='slides_node_express.html#/6'>◻</a></p>
<h3 id="routes"><a class="anchorlink" href="#routes"><span>4.2</span> Routes</a></h3><p>In more complex MVC (Model-View-Controller) frameworks, controllers and routing are treated as separate entities.
However, in Express.js, both of these tasks are managed by routes.</p><p>It's common practice to divide routing into multiple files.</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">// in file app.js</span>
<span class="kd">var</span> <span class="nx">indexRouter</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">./routes/index</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">usersRouter</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">./routes/users</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">app</span><span class="p">.</span><span class="nf">use</span><span class="p">(</span><span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">,</span> <span class="nx">indexRouter</span><span class="p">);</span>
<span class="nx">app</span><span class="p">.</span><span class="nf">use</span><span class="p">(</span><span class="dl">'</span><span class="s1">/users</span><span class="dl">'</span><span class="p">,</span> <span class="nx">usersRouter</span><span class="p">);</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// in file app.js
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
app.use('/', indexRouter);
app.use('/users', usersRouter);
">Copy</button>
</div>
<div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">// in ./routes/users.js</span>
<span class="kd">var</span> <span class="nx">express</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">express</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">router</span> <span class="o">=</span> <span class="nx">express</span><span class="p">.</span><span class="nc">Router</span><span class="p">();</span>
<span class="cm">/* GET users listing. */</span>
<span class="nx">router</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">next</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">res</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">respond with a resource</span><span class="dl">'</span><span class="p">);</span>
<span class="p">});</span>
<span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nx">router</span><span class="p">;</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// in ./routes/users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
">Copy</button>
</div>
<p>The routes in file users.js are relative to the
base-route set in app.js.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-7' href='slides_node_express.html#/7'>◻</a></p>
<h3 id="serving-json"><a class="anchorlink" href="#serving-json"><span>4.3</span> Serving JSON</a></h3><p>The express.json middleware will convert
a javascript data structure into JSON and
serve it with the appropriate content type:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">// in file app.js</span>
<span class="nx">app</span><span class="p">.</span><span class="nf">use</span><span class="p">(</span><span class="nx">express</span><span class="p">.</span><span class="nf">json</span><span class="p">());</span>
<span class="c1">// in ./routes/users.js</span>
<span class="kd">var</span> <span class="nx">users</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">'</span><span class="s1">konsti</span><span class="dl">'</span> <span class="p">}</span>
<span class="p">,</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">'</span><span class="s1">johannes</span><span class="dl">'</span> <span class="p">}</span>
<span class="p">,</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">'</span><span class="s1">lara</span><span class="dl">'</span> <span class="p">}</span>
<span class="p">,</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">'</span><span class="s1">tanja</span><span class="dl">'</span> <span class="p">}</span>
<span class="p">];</span>
<span class="nx">router</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">next</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">res</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="nx">users</span><span class="p">);</span>
<span class="p">});</span>
<span class="c1">// result in browser:</span>
<span class="p">[{</span><span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span><span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span><span class="dl">"</span><span class="s2">konsti</span><span class="dl">"</span><span class="p">},{</span><span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span><span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span><span class="dl">"</span><span class="s2">johannes</span><span class="dl">"</span><span class="p">},{</span><span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span><span class="mi">3</span><span class="p">,</span><span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span><span class="dl">"</span><span class="s2">lara</span><span class="dl">"</span><span class="p">},{</span><span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span><span class="mi">4</span><span class="p">,</span><span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span><span class="dl">"</span><span class="s2">tanja</span><span class="dl">"</span><span class="p">}]</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// in file app.js
app.use(express.json());
// in ./routes/users.js
var users = [
{ name: 'konsti' }
, { name: 'johannes' }
, { name: 'lara' }
, { name: 'tanja' }
];
router.get('/', function(req, res, next) {
res.send(users);
});
// result in browser:
[{"id":1,"name":"konsti"},{"id":2,"name":"johannes"},{"id":3,"name":"lara"},{"id":4,"name":"tanja"}]
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-8' href='slides_node_express.html#/8'>◻</a></p>
<h3 id="more-routing"><a class="anchorlink" href="#more-routing"><span>4.4</span> More Routing</a></h3><p>URLs can contain parameters in two ways: as query parameters:</p><p><a href="http://localhost:3000/users?name=Jin">http://localhost:3000/users?name=Jin</a></p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">// in ./routes/users.js</span>
<span class="nx">app</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">,</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="kd">let</span> <span class="nx">name</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">query</span><span class="p">.</span><span class="nx">name</span><span class="p">;</span> <span class="c1">// Jin</span>
<span class="c1">// ...</span>
<span class="p">});</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// in ./routes/users.js
app.get('/', (req, res) => {
let name = req.query.name; // Jin
// ...
});
">Copy</button>
</div>
<p>Sometimes we want to identify parts of the URL:</p><p><a href="http://localhost:3000/users/3">http://localhost:3000/users/3</a></p><p>Here we can use express route parameters:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">// in ./routes/users.js</span>
<span class="cm">/* GET one users - use :id in the path, and read req.params.id */</span>
<span class="nx">router</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/:id</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">next</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">user</span> <span class="o">=</span> <span class="nx">users</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span> <span class="nx">u</span> <span class="o">=></span> <span class="nx">u</span><span class="p">.</span><span class="nx">id</span> <span class="o">==</span> <span class="nx">req</span><span class="p">.</span><span class="nx">params</span><span class="p">.</span><span class="nx">id</span><span class="p">)</span>
<span class="nx">res</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="nx">user</span><span class="p">);</span>
<span class="p">});</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// in ./routes/users.js
/* GET one users - use :id in the path, and read req.params.id */
router.get('/:id', function(req, res, next) {
var user = users.find( u => u.id == req.params.id)
res.send(user);
});
">Copy</button>
</div>
<p>Use the http methods as function names, or use <code>all</code> to catch
all methods:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">// in ./routes/users.js</span>
<span class="cm">/* POST one users - use :id in the path, and read req.params.id */</span>
<span class="nx">router</span><span class="p">.</span><span class="nf">post</span><span class="p">(</span><span class="dl">'</span><span class="s1">/:id</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">,</span> <span class="nx">next</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">var</span> <span class="nx">user</span> <span class="o">=</span> <span class="nx">users</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span> <span class="nx">u</span> <span class="o">=></span> <span class="nx">u</span><span class="p">.</span><span class="nx">id</span> <span class="o">==</span> <span class="nx">req</span><span class="p">.</span><span class="nx">params</span><span class="p">.</span><span class="nx">id</span><span class="p">)</span>
<span class="nx">res</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="nx">user</span><span class="p">);</span>
<span class="p">});</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// in ./routes/users.js
/* POST one users - use :id in the path, and read req.params.id */
router.post('/:id', function(req, res, next) {
var user = users.find( u => u.id == req.params.id)
res.send(user);
});
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-9' href='slides_node_express.html#/9'>◻</a></p>
<h3 id="set-up-cors-for-a-frontend"><a class="anchorlink" href="#set-up-cors-for-a-frontend"><span>4.5</span> Set up CORS for a frontend</a></h3></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-10' href='slides_node_express.html#/10'>◻</a></p>
<h2 id="server-rendered-html"><a class="anchorlink" href="#server-rendered-html"><span>5</span> Server rendered HTML</a></h2><p>express supports several different templating engines.</p></div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-11' href='slides_node_express.html#/11'>◻</a></p>
<h3 id="views-with-jade"><a class="anchorlink" href="#views-with-jade"><span>5.1</span> Views with JADE</a></h3><div class="interstitial code">
<pre><code class="highlight plaintext">app.get('/', function (req, res) {
res.render('index', {user: 'Welt'});
});
</code></pre>
<button class="clipboard-button" data-clipboard-text="app.get('/', function (req, res) {
res.render('index', {user: 'Welt'});
});
">Copy</button>
</div>
<div class="interstitial code">
<pre><code class="highlight plaintext">extends layout
block content
h1 Hallo #{user}
a(href='https://google.com') Google
ul
- for (var x = 0; x < 3; x++)
li bla
</code></pre>
<button class="clipboard-button" data-clipboard-text="extends layout
block content
h1 Hallo #{user}
a(href='https://google.com') Google
ul
- for (var x = 0; x < 3; x++)
li bla
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-12' href='slides_node_express.html#/12'>◻</a></p>
<h3 id="working-with-data"><a class="anchorlink" href="#working-with-data"><span>5.2</span> Working with data</a></h3><p>Pass data to the views</p><div class="interstitial code">
<pre><code class="highlight plaintext">res.render('index', { title: 'Customer List' });
</code></pre>
<button class="clipboard-button" data-clipboard-text="res.render('index', { title: 'Customer List' });
">Copy</button>
</div>
<p>Read data from form</p><div class="interstitial code">
<pre><code class="highlight plaintext">app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(req, res){
var userName = req.body.username;
res.send(`Hello ${username}<br><a href="/">Try again.</a>`);
});
</code></pre>
<button class="clipboard-button" data-clipboard-text="app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(req, res){
var userName = req.body.username;
res.send(`Hello ${username}<br><a href="/">Try again.</a>`);
});
">Copy</button>
</div>
<p>Read and send files</p><div class="interstitial code">
<pre><code class="highlight plaintext">let filePath = req.files.picture.path;
res.sendfile(filePath); // also: sets Content-Type from ext
// res.download(filePath); // same, as attachment, size
</code></pre>
<button class="clipboard-button" data-clipboard-text="let filePath = req.files.picture.path;
res.sendfile(filePath); // also: sets Content-Type from ext
// res.download(filePath); // same, as attachment, size
">Copy</button>
</div>
<p>Data for all views</p><div class="interstitial code">
<pre><code class="highlight plaintext">app.locals.clock = new Date().toUTCString();
</code></pre>
<button class="clipboard-button" data-clipboard-text="app.locals.clock = new Date().toUTCString();
">Copy</button>
</div>
<p>clock is now available in all views:</p><div class="interstitial code">
<pre><code class="highlight plaintext">p This Server started at #{clock}
</code></pre>
<button class="clipboard-button" data-clipboard-text="p This Server started at #{clock}
">Copy</button>
</div>
</div>
<div class='slide'>
<p class='slide_break_block'><a class='slide_break' id='slide-13' href='slides_node_express.html#/13'>◻</a></p>
<h2 id="see-also"><a class="anchorlink" href="#see-also"><span>6</span> See Also</a></h2>
<ul>
<li><a href="https://expressjs.com/en/resources/frameworks.html">frameworks recommended by express</a></li>
</ul>
</div>
</div>
</div>
</main>
<hr class="hide" />
<footer id="page_footer">
<div class="wrapper">
<p class="copyright">published under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/at/deed.de">creative commons by-nc-sa</a> in 2012-2025 by <a href="https://brigitte-jellinek.at">Brigitte Jellinek</a>.
</p>
<p>If you want to contribute: <a href="https://github.com/backend-development/backend-development-textbook/fork">fork the source on github</a>
</p>
<p>Favicon "backend development" by Arkinasi from <a href="https://thenounproject.com/browse/icons/term/backend-development/" target="_blank" title="backend development Icons">Noun Project</a> (CC BY 3.0)</p>
</div>
</footer>
</body>
</html>