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
|
---
title: 'Express Tutorial Part 4: Routes and controllers'
slug: Learn/Server-side/Express_Nodejs/routes
translation_of: Learn/Server-side/Express_Nodejs/routes
---
<div>{{LearnSidebar}}</div>
<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}</div>
<p class="summary">У цій статті ми настроїмо (URL handling code) з "штучною" функцією обробки всіх можливих шляхів (endpoints) які потрібні у <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">LocalLibrary</a> сайті. У підсумку ми матимемо модульну структуру відладки для всіх шляхів, яку ми зможемо використати у наступній статті. Ми матимемо хороше розуміння, як створювати модульну структуру для шляхів які використовує Express!</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Передумови:</th>
<td>Прочитайте <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a>. Закінчіть попередні частини (включаючи <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a>).</td>
</tr>
<tr>
<th scope="row">Мета:</th>
<td>Вміти створити простий шляхи. Настроїти обробку всі URL шляхів.</td>
</tr>
</tbody>
</table>
<h2 id="Overview">Overview</h2>
<p>In the <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">last tutorial article</a> we defined <em>Mongoose</em> models to interact with the database, and used a (standalone) script to create some initial library records. We can now write the code to present that information to users. The first thing we need to do is determine what information we want to be able to display in our pages, and then define appropriate URLs for returning those resources. Then we're going to need to create the routes (URL handlers) and views (templates) to display those pages.</p>
<p>The diagram below is provided as a reminder of the main flow of data and things that need to be implemented when handling an HTTP request/response. In addition to the views and routes the diagram shows "controllers" — functions that separate out the code to route requests from the code that actually processes requests.</p>
<p>As we've already created the models, the main things we'll need to create are:</p>
<ul>
<li>"Routes" to forward the supported requests (and any information encoded in request URLs) to the appropriate controller functions.</li>
<li>Controller functions to get the requested data from the models, create an HTML page displaying the data, and return it to the user to view in the browser.</li>
<li>Views (templates) used by the controllers to render the data.</li>
</ul>
<p><img alt="" src="https://mdn.mozillademos.org/files/14456/MVC%20Express.png" style="height: 460px; width: 800px;"></p>
<p>Ultimately we might have pages to show lists and detail information for books, genres, authors and bookinstances, along with pages to create, update, and delete records. That's a lot to document in one article. Therefore most of this article will concentrate on setting up our routes and controllers to return "dummy" content. We'll extend the controller methods in our subsequent articles to work with model data.</p>
<p>The first section below provides a brief "primer" on how to use the Express <a href="http://expressjs.com/en/4x/api.html#router">Router</a> middleware. We'll then use that knowledge in the following sections when we set up the LocalLibrary routes.</p>
<h2 id="Routes_primer">Routes primer</h2>
<p>A route is a section of Express code that associates an HTTP verb (<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, etc.), an URL path/pattern, and a function that is called to handle that pattern.</p>
<p>There are several ways to create routes. For this tutorial we're going to use the <code><a href="http://expressjs.com/en/guide/routing.html#express-router">express.Router</a></code> middleware as it allows us to group the route handlers for a particular part of a site together and access them using a common route-prefix. We'll keep all our library-related routes in a "catalog" module, and, if we add routes for handling user accounts or other functions, we can keep them grouped separately.</p>
<div class="note">
<p><strong>Note:</strong> We discussed Express application routes briefly in our <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Creating_route_handlers">Express Introduction > Creating route handlers</a>. Other than providing better support for modularization (as discussed in the first subsection below), using <em>Router</em> is very similar to defining routes directly on the <em>Express application object</em>.</p>
</div>
<p>The rest of this section provides an overview of how the <code>Router</code> can be used to define the routes.</p>
<h3 id="Defining_and_using_separate_route_modules">Defining and using separate route modules</h3>
<p>The code below provides a concrete example of how we can create a route module and then use it in an <em>Express</em> application.</p>
<p>First we create routes for a wiki in a module named <strong>wiki.js</strong>. The code first imports the Express application object, uses it to get a <code>Router</code> object and then adds a couple of routes to it using the <code>get()</code> method. Last of all the module exports the <code>Router</code> object.</p>
<pre class="brush: js"><code>// wiki.js - Wiki route module.
var express = require('express');
var router = express.Router();
// Home page route.
router.get('/', function (req, res) {
res.send('Wiki home page');
})
// About page route.
router.get('/about', function (req, res) {
res.send('About this wiki');
})
module.exports = router;</code>
</pre>
<div class="note">
<p><strong>Note:</strong> Above we are defining our route handler callbacks directly in the router functions. In the LocalLibrary we'll define these callbacks in a separate controller module.</p>
</div>
<p>To use the router module in our main app file we first <code>require()</code> the route module (<strong>wiki.js</strong>). We then call <code>use()</code> on the <em>Express</em> application to add the Router to the middleware handling path, specifying an URL path of 'wiki'.</p>
<pre class="brush: js"><code>var wiki = require('./wiki.js');
// ...
app.use('/wiki', wiki);</code></pre>
<p>The two routes defined in our wiki route module are then accessible from <code>/wiki/</code> and <code>/wiki/about/</code>.</p>
<h3 id="Route_functions">Route functions</h3>
<p>Our module above defines a couple of typical route functions. The "about" route (reproduced below) is defined using the <code>Router.get()</code> method, which responds only to HTTP GET requests. The first argument to this method is the URL path while the second is a callback function that will be invoked if an HTTP GET request with the path is received.</p>
<pre class="brush: js"><code>router.get('/about', function (req, res) {
res.send('About this wiki');
})</code>
</pre>
<p>The callback takes three arguments (usually named as shown: <code>req</code>, <code>res</code>, <code>next</code>), that will contain the HTTP Request object, HTTP response, and the <em>next</em> function in the middleware chain.</p>
<div class="note">
<p><strong>Note:</strong> Router functions are <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Using_middleware">Express middleware</a>, which means that they must either complete (respond to) the request or call the <code>next</code> function in the chain. In the case above we complete the request using <code>send()</code>, so the <code>next</code> argument is not used (and we choose not to specify it).</p>
<p>The router function above takes a single callback, but you can specify as many callback arguments as you want, or an array of callback functions. Each function is part of the middleware chain, and will be called in the order it is added to the chain (unless a preceding function completes the request).</p>
</div>
<p>The callback function here calls <code><a href="https://expressjs.com/en/4x/api.html#res.send">send()</a></code> on the response to return the string "About this wiki" when we receive a GET request with the path ('<code>/about'</code>). There are a <a href="https://expressjs.com/en/guide/routing.html#response-methods">number of other response methods</a> for ending the request/response cycle. For example, you could call <code><a href="https://expressjs.com/en/4x/api.html#res.json">res.json()</a></code> to send a JSON response or <code><a href="https://expressjs.com/en/4x/api.html#res.sendFile">res.sendFile()</a></code> to send a file. The response method that we'll be using most often as we build up the library is <a href="https://expressjs.com/en/4x/api.html#res.render">render()</a>, which creates and returns HTML files using templates and data—we'll talk a lot more about that in a later article!</p>
<h3 id="HTTP_verbs">HTTP verbs</h3>
<p>The example routes above use the <code>Router.get()</code> method to respond to HTTP GET requests with a certain path.</p>
<p>The <code>Router</code> also provides route methods for all the other HTTP verbs, that are mostly used in exactly the same way: <code>post()</code>, <code>put()</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-</code><code>search()</code>, <code>notify()</code>, <code>subscribe()</code>, <code>unsubscribe()</code>, <code>patch()</code>, <code>search()</code>, and <code>connect()</code>.</p>
<p>For example, the code below behaves just like the previous <code>/about</code> route, but only responds to HTTP POST requests.</p>
<pre class="brush: js"><code>router.post('/about', function (req, res) {
res.send('About this wiki');
})</code></pre>
<h3 id="Route_paths">Route paths</h3>
<p>The route paths define the endpoints at which requests can be made. The examples we've seen so far have just been strings, and are used exactly as written: '/', '/about', '/book', '/any-random.path'.</p>
<p>Route paths can also be string patterns. String patterns use a subset of regular expression syntax to define <em>patterns</em> of endpoints that will be matched. The subset is listed below (note that the hyphen (<code>-</code>) and the dot (<code>.</code>) are interpreted literally by string-based paths):</p>
<ul>
<li>? : The endpoint must have 0 or 1 of the preceding character. E.g. a route path of <code>'/ab?cd'</code> will match endpoints <code>acd</code> or <code>abcd</code>.</li>
<li>+ : The endpoint must have 1 or more of the preceding character. E.g. a route path of <code>'/ab+cd'</code> will match endpoints <code>abcd</code>, <code>abbcd</code>, <code>abbbcd</code>, and so on.</li>
<li>* : The endpoint may have an arbitrary string where the * character is placed. E.g. a route path of <code>'ab*cd'</code> will match endpoints <code>abcd</code>, <code>abXcd</code>, <code>abSOMErandomTEXTcd</code>, and so on.</li>
<li>() : Grouping match on a set of characters to perform another operation on. E.g. <code>'/ab(cd)?e'</code> will peform a ? match on (cd) —it will match <code>abe</code> and <code>abcde</code>.</li>
</ul>
<p>The route paths can also be JavaScript <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">regular expressions</a>. For example, the route path below will match <code>catfish </code>and <code>dogfish</code>, but not <code>catflap</code>, <code>catfishhead</code>, and so on. Note that the path for a regular expression uses regular expression syntax (it is not a quoted string as in the previous cases).</p>
<pre class="brush: js"><code>app.get(/.*fish$/, function (req, res) {
...
})</code></pre>
<div class="note">
<p><strong>Note:</strong> Most of our routes for the LocalLibrary will simply use strings and not string patterns and regular expressions. We'll also use route parameters as discussed in the next section.</p>
</div>
<h3 id="Route_parameters">Route parameters</h3>
<p>Route parameters are <em>named URL segments</em> used to capture the values specified at their position in the URL. The named segments are prefixed with a colon and then the name (e.g. <code>/<strong>:</strong>your_parameter_name/</code>. The captured values are stored in the <code>req.params</code> object using the parameter names as keys (e.g. <code>req.params.your_parameter_name</code>).</p>
<p>So for example, consider a URL encoded to contain information about users and books: <code>http://localhost:3000/users/34/books/8989</code>. We can extract this information as shown below, with the <code>userId</code> and <code>bookId</code> path parameters:</p>
<pre><code>app.get('/users/:userId/books/:bookId', function (req, res) {
// Access userId via: req.params.userId
// Access bookId via: req.params.bookId
res.send(req.params);
})
</code></pre>
<p>The names of route parameters must be made up of “word characters” (A-Z, a-z, 0-9, and _).</p>
<div class="note">
<p><strong>Note:</strong> The URL <em>/book/create</em> will be matched by a route like <code>/book/:bookId</code> (which will extract a "bookId" value of '<code>create</code>'). The first route that matches an incoming URL will be used, so if you want to process <code>/book/create</code> URLs separately, their route handler must be defined before your <code>/book/:bookId</code> route.</p>
</div>
<p>That's all you need to get started with routes - if needed you can find more information in the Express docs: <a href="http://expressjs.com/en/starter/basic-routing.html">Basic routing</a> and <a href="http://expressjs.com/en/guide/routing.html">Routing guide</a>. The following sections show how we'll set up our routes and controllers for the LocalLibrary.</p>
<h2 id="Routes_needed_for_the_LocalLibrary">Routes needed for the LocalLibrary</h2>
<p>The URLs that we're ultimately going to need for our pages are listed below, where <em>object</em> is replaced by the name of each of our models (book, bookinstance, genre, author), <em>objects</em> is the plural of object, and <em>id</em> is the unique instance field (<code>_id</code>) that is given to each Mongoose model instance by default.</p>
<ul>
<li><code>catalog/</code> — The home/index page.</li>
<li><code>catalog/<objects>/</code> — The list of all books, bookinstances, genres, or authors (e.g. /<code>catalog/books/</code>, /<code>catalog/genres/</code>, etc.)</li>
<li><code>catalog/<object>/<em><id></em></code> — The detail page for a specific book, bookinstance, genre, or author with the given <code><em>_id</em></code> field value (e.g. <code>/catalog/book/584493c1f4887f06c0e67d37)</code>.</li>
<li><code>catalog/<object>/create</code> — The form to create a new book, bookinstance, genre, or author (e.g. <code>/catalog/book/create)</code>.</li>
<li><code>catalog/<object>/<em><id></em>/update</code> — The form to update a specific book, bookinstance, genre, or author with the given <code><em>_id</em></code> field value (e.g. <code>/catalog/book/584493c1f4887f06c0e67d37/update)</code>.</li>
<li><code>catalog/<object>/<em><id></em>/delete</code> — The form to delete a specific book, bookinstance, genre, author with the given <code><em>_id</em></code> field value (e.g. <code>/catalog/book/584493c1f4887f06c0e67d37/delete)</code>.</li>
</ul>
<p>The first home page and list pages don't encode any additional information. While the results returned will depend on the model type and the content in the database, the queries run to get the information will always be the same (similarly the code run for object creation will always be similar).</p>
<p>By contrast the other URLs are used to act on a specific document/model instance—these encode the identity of the item in the URL (shown as <code><em><id></em></code> above). We'll use path parameters to extract the encoded information and pass it to the route handler (and in a later article we'll use this to dynamically determine what information to get from the database). By encoding the information in our URL we only need one route for every resource of a particular type (e.g. one route to handle the display of every single book item).</p>
<div class="note">
<p><strong>Note</strong>: Express allows you to construct your URLs any way you like — you can encode information in the body of the URL as shown above or use URL <code>GET</code> parameters (e.g. <code>/book/?id=6</code>). Whichever approach you use, the URLs should be kept clean, logical and readable (<a href="https://www.w3.org/Provider/Style/URI">check out the W3C advice here</a>).</p>
</div>
<p>Next we create our route handler callback functions and route code for all the above URLs.</p>
<h2 id="Create_the_route-handler_callback_functions">Create the route-handler callback functions</h2>
<p>Before we define our routes, we'll first create all the dummy/skeleton callback functions that they will invoke. The callbacks will be stored in separate "controller" modules for Books, BookInstances, Genres, and Authors (you can use any file/module structure, but this seems an appropriate granularity for this project).</p>
<p>Start by creating a folder for our controllers in the project root (<strong>/controllers</strong>) and then create separate controller files/modules for handling each of the models:</p>
<pre>/express-locallibrary-tutorial //the project root
<strong>/controllers</strong>
<strong>authorController.js</strong>
<strong>bookController.js</strong>
<strong>bookinstanceController.js</strong>
<strong>genreController.js</strong></pre>
<h3 id="Author_controller">Author controller</h3>
<p>Open the <strong>/controllers/authorController.js</strong> file and copy in the following code:</p>
<pre class="brush: js">var Author = require('../models/author');
// Display list of all Authors.
exports.author_list = function(req, res) {
res.send('NOT IMPLEMENTED: Author list');
};
// Display detail page for a specific Author.
exports.author_detail = function(req, res) {
res.send('NOT IMPLEMENTED: Author detail: ' + req.params.id);
};
// Display Author create form on GET.
exports.author_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: Author create GET');
};
// Handle Author create on POST.
exports.author_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: Author create POST');
};
// Display Author delete form on GET.
exports.author_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: Author delete GET');
};
// Handle Author delete on POST.
exports.author_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: Author delete POST');
};
// Display Author update form on GET.
exports.author_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: Author update GET');
};
// Handle Author update on POST.
exports.author_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: Author update POST');
};
</pre>
<p>The module first requires the model that we'll later be using to access and update our data. It then exports functions for each of the URLs we wish to handle (the create, update and delete operations use forms, and hence also have additional methods for handling form post requests — we'll discuss those methods in the "forms article" later on).</p>
<p>All the functions have the standard form of an <em>Express middleware function</em>, with arguments for the request, response, and the <code>next</code> function to be called if the method does not complete the request cycle (in all these cases it does!). The methods simply return a string indicating that the associated page has not yet been created. If a controller function is expected to receive path parameters, these are output in the message string (see <code>req.params.id</code> above).</p>
<h4 id="BookInstance_controller">BookInstance controller</h4>
<p>Open the <strong>/controllers/bookinstanceController.js</strong> file and copy in the following code (this follows an identical pattern to the <code>Author</code> controller module):</p>
<pre class="brush: js">var BookInstance = require('../models/bookinstance');
// Display list of all BookInstances.
exports.bookinstance_list = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance list');
};
// Display detail page for a specific BookInstance.
exports.bookinstance_detail = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance detail: ' + req.params.id);
};
// Display BookInstance create form on GET.
exports.bookinstance_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance create GET');
};
// Handle BookInstance create on POST.
exports.bookinstance_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance create POST');
};
// Display BookInstance delete form on GET.
exports.bookinstance_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance delete GET');
};
// Handle BookInstance delete on POST.
exports.bookinstance_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance delete POST');
};
// Display BookInstance update form on GET.
exports.bookinstance_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance update GET');
};
// Handle bookinstance update on POST.
exports.bookinstance_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: BookInstance update POST');
};
</pre>
<h4 id="Genre_controller">Genre controller</h4>
<p>Open the <strong>/controllers/genreController.js</strong> file and copy in the following text (this follows an identical pattern to the <code>Author</code> and <code>BookInstance</code> files):</p>
<pre class="brush: js">var Genre = require('../models/genre');
// Display list of all Genre.
exports.genre_list = function(req, res) {
res.send('NOT IMPLEMENTED: Genre list');
};
// Display detail page for a specific Genre.
exports.genre_detail = function(req, res) {
res.send('NOT IMPLEMENTED: Genre detail: ' + req.params.id);
};
// Display Genre create form on GET.
exports.genre_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: Genre create GET');
};
// Handle Genre create on POST.
exports.genre_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: Genre create POST');
};
// Display Genre delete form on GET.
exports.genre_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: Genre delete GET');
};
// Handle Genre delete on POST.
exports.genre_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: Genre delete POST');
};
// Display Genre update form on GET.
exports.genre_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: Genre update GET');
};
// Handle Genre update on POST.
exports.genre_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: Genre update POST');
};
</pre>
<h4 id="Book_controller">Book controller</h4>
<p>Open the <strong>/controllers/bookController.js</strong> file and copy in the following code. This follows the same pattern as the other controller modules, but additionally has an <code>index()</code> function for displaying the site welcome page:</p>
<pre class="brush: js">var Book = require('../models/book');
<strong>exports.index = function(req, res) {
res.send('NOT IMPLEMENTED: Site Home Page');
};</strong>
// Display list of all books.
exports.book_list = function(req, res) {
res.send('NOT IMPLEMENTED: Book list');
};
// Display detail page for a specific book.
exports.book_detail = function(req, res) {
res.send('NOT IMPLEMENTED: Book detail: ' + req.params.id);
};
// Display book create form on GET.
exports.book_create_get = function(req, res) {
res.send('NOT IMPLEMENTED: Book create GET');
};
// Handle book create on POST.
exports.book_create_post = function(req, res) {
res.send('NOT IMPLEMENTED: Book create POST');
};
// Display book delete form on GET.
exports.book_delete_get = function(req, res) {
res.send('NOT IMPLEMENTED: Book delete GET');
};
// Handle book delete on POST.
exports.book_delete_post = function(req, res) {
res.send('NOT IMPLEMENTED: Book delete POST');
};
// Display book update form on GET.
exports.book_update_get = function(req, res) {
res.send('NOT IMPLEMENTED: Book update GET');
};
// Handle book update on POST.
exports.book_update_post = function(req, res) {
res.send('NOT IMPLEMENTED: Book update POST');
};
</pre>
<h2 id="Create_the_catalog_route_module">Create the catalog route module</h2>
<p>Next we create <em>routes</em> for all the URLs <a href="#local_libary_routes">needed by the LocalLibrary website</a>, which will call the controller functions we defined in the previous section.</p>
<p>The skeleton already has a <strong>./routes</strong> folder containing routes for the <em>index</em> and <em>users</em>. Create another route file — <strong>catalog.js</strong> — inside this folder, as shown.</p>
<pre>/express-locallibrary-tutorial //the project root
/routes
index.js
users.js
<strong>catalog.js</strong></pre>
<p>Open <strong>/routes/</strong><strong>catalog.js</strong> and copy in the code below:</p>
<pre class="brush: js"><strong>var express = require('express');
var router = express.Router();
</strong>
// Require controller modules.
var book_controller = require('../controllers/bookController');
var author_controller = require('../controllers/authorController');
var genre_controller = require('../controllers/genreController');
var book_instance_controller = require('../controllers/bookinstanceController');
/// BOOK ROUTES ///
// GET catalog home page.
router.get('/', book_controller.index);
// GET request for creating a Book. NOTE This must come before routes that display Book (uses id).
router.get('/book/create', book_controller.book_create_get);
// POST request for creating Book.
router.post('/book/create', book_controller.book_create_post);
// GET request to delete Book.
router.get('/book/:id/delete', book_controller.book_delete_get);
// POST request to delete Book.
router.post('/book/:id/delete', book_controller.book_delete_post);
// GET request to update Book.
router.get('/book/:id/update', book_controller.book_update_get);
// POST request to update Book.
router.post('/book/:id/update', book_controller.book_update_post);
// GET request for one Book.
router.get('/book/:id', book_controller.book_detail);
// GET request for list of all Book items.
router.get('/books', book_controller.book_list);
/// AUTHOR ROUTES ///
// GET request for creating Author. NOTE This must come before route for id (i.e. display author).
router.get('/author/create', author_controller.author_create_get);
// POST request for creating Author.
router.post('/author/create', author_controller.author_create_post);
// GET request to delete Author.
router.get('/author/:id/delete', author_controller.author_delete_get);
// POST request to delete Author.
router.post('/author/:id/delete', author_controller.author_delete_post);
// GET request to update Author.
router.get('/author/:id/update', author_controller.author_update_get);
// POST request to update Author.
router.post('/author/:id/update', author_controller.author_update_post);
// GET request for one Author.
router.get('/author/:id', author_controller.author_detail);
// GET request for list of all Authors.
router.get('/authors', author_controller.author_list);
/// GENRE ROUTES ///
// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id).
router.get('/genre/create', genre_controller.genre_create_get);
//POST request for creating Genre.
router.post('/genre/create', genre_controller.genre_create_post);
// GET request to delete Genre.
router.get('/genre/:id/delete', genre_controller.genre_delete_get);
// POST request to delete Genre.
router.post('/genre/:id/delete', genre_controller.genre_delete_post);
// GET request to update Genre.
router.get('/genre/:id/update', genre_controller.genre_update_get);
// POST request to update Genre.
router.post('/genre/:id/update', genre_controller.genre_update_post);
// GET request for one Genre.
router.get('/genre/:id', genre_controller.genre_detail);
// GET request for list of all Genre.
router.get('/genres', genre_controller.genre_list);
/// BOOKINSTANCE ROUTES ///
// GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id).
router.get('/bookinstance/create', book_instance_controller.bookinstance_create_get);
// POST request for creating BookInstance.
router.post('/bookinstance/create', book_instance_controller.bookinstance_create_post);
// GET request to delete BookInstance.
router.get('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_get);
// POST request to delete BookInstance.
router.post('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_post);
// GET request to update BookInstance.
router.get('/bookinstance/:id/update', book_instance_controller.bookinstance_update_get);
// POST request to update BookInstance.
router.post('/bookinstance/:id/update', book_instance_controller.bookinstance_update_post);
// GET request for one BookInstance.
router.get('/bookinstance/:id', book_instance_controller.bookinstance_detail);
// GET request for list of all BookInstance.
router.get('/bookinstances', book_instance_controller.bookinstance_list);
<strong>module.exports = router;</strong>
</pre>
<p>The module requires Express and then uses it to create a <code>Router</code> object. The routes are all set up on the router, which is then exported.</p>
<p>The routes are defined either using <code>.get()</code> or <code>.post()</code> methods on the router object. All the paths are defined using strings (we don't use string patterns or regular expressions). Routes that act on some specific resource (e.g. book) use path parameters to get the object id from the URL.</p>
<p>The handler functions are all imported from the controller modules we created in the previous section.</p>
<h3 id="Update_the_index_route_module">Update the index route module</h3>
<p>We've set up all our new routes, but we still have a route to the original page. Let's instead redirect this to the new index page that we've created at the path '/catalog'.</p>
<p>Open <strong>/routes/index.js</strong> and replace the existing route with the function below.</p>
<pre class="brush: js">// GET home page.
router.get('/', function(req, res) {
res.redirect('/catalog');
});</pre>
<div class="note">
<p><strong>Note:</strong> This is our first use of the <a href="https://expressjs.com/en/4x/api.html#res.redirect">redirect()</a> response method. This redirects to the specified page, by default sending HTTP status code "302 Found". You can change the status code returned if needed, and supply either absolute or relative paths.</p>
</div>
<h3 id="Update_app.js">Update app.js</h3>
<p>The last step is to add the routes to the middleware chain. We do this in <code>app.js</code>.</p>
<p>Open <strong>app.js</strong> and require the catalog route below the other routes (add the third line shown below, underneath the other two):</p>
<pre class="brush: js">var index = require('./routes/index');
var users = require('./routes/users');
<strong>var catalog = require('./routes/catalog'); //Import routes for "catalog" area of site</strong></pre>
<p>Next, add the catalog route to the middleware stack below the other routes (add the third line shown below, underneath the other two):</p>
<pre class="brush: js">app.use('/', index);
app.use('/users', users);
<strong>app.use('/catalog', catalog); // Add catalog routes to middleware chain.</strong></pre>
<div class="note">
<p><strong>Note:</strong> We have added our catalog module at a path <code>'/catalog'</code>. This is prepended to all of the paths defined in the catalog module. So for example, to access a list of books, the URL will be: <code>/catalog/books/</code>.</p>
</div>
<p>That's it. We should now have routes and skeleton functions enabled for all the URLs that we will eventually support on the LocalLibrary website.</p>
<h3 id="Testing_the_routes">Testing the routes</h3>
<p>To test the routes, first start the website using your usual approach</p>
<ul>
<li>The default method
<pre class="brush: bash"><code>// Windows
SET DEBUG=express-locallibrary-tutorial:* & npm start
// macOS or Linux
DEBUG=express-locallibrary-tutorial:* npm start</code>
</pre>
</li>
<li>If you previously set up <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">nodemon</a>, you can instead use:
<pre><code>// Windows
SET DEBUG=express-locallibrary-tutorial:* & npm <strong>run devstart</strong>
// macOS or Linux
</code>DEBUG=express-locallibrary-tutorial:* npm <strong style="font-family: inherit; font-size: 1rem;">run devstart</strong>
</pre>
</li>
</ul>
<p>Then navigate to a number of LocalLibrary URLs, and verify that you don't get an error page (HTTP 404). A small set of URLs are listed below for your convenience:</p>
<ul>
<li><a href="http://localhost:3000/">http://localhost:3000/</a></li>
<li><a href="http://localhost:3000/catalog">http://localhost:3000/catalog</a></li>
<li><a href="http://localhost:3000/catalog/books">http://localhost:3000/catalog/books</a></li>
<li><a href="http://localhost:3000/catalog/bookinstances/">http://localhost:3000/catalog/bookinstances/</a></li>
<li><a href="http://localhost:3000/catalog/authors/">http://localhost:3000/catalog/authors/</a></li>
<li><a href="http://localhost:3000/catalog/genres/">http://localhost:3000/catalog/genres/</a></li>
<li><a href="http://localhost:3000/catalog/book/5846437593935e2f8c2aa226/">http://localhost:3000/catalog/book/5846437593935e2f8c2aa226</a></li>
<li><a href="http://localhost:3000/catalog/book/create">http://localhost:3000/catalog/book/create</a></li>
</ul>
<h2 id="Summary">Summary</h2>
<p>We've now created all the routes for our site, along with dummy controller functions that we can populate with a full implementation in later articles. Along the way we've learned a lot of fundamental information about Express routes, and some approaches for structuring our routes and controllers.</p>
<p>In our next article we'll create a proper welcome page for the site, using views (templates) and information stored in our models.</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="http://expressjs.com/en/starter/basic-routing.html">Basic routing</a> (Express docs)</li>
<li><a href="http://expressjs.com/en/guide/routing.html">Routing guide</a> (Express docs)</li>
</ul>
<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}</p>
<p> </p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li>
<li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li>
</ul>
<p> </p>
|