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
|
---
title: 'Express Tutorial Parte 2: Criando a estrutura do website'
slug: Learn/Server-side/Express_Nodejs/skeleton_website
translation_of: Learn/Server-side/Express_Nodejs/skeleton_website
---
<div>{{LearnSidebar}}</div>
<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}</p>
<p class="summary">Neste segundo <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial</a> , mostrará como criar a estrutura do website que depois você poderá colocar <em>templates,</em> chamadas de banco de dados ou rotas específicas.</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Pré-requisitos:</th>
<td><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Preparar o ambiente de desenvolvimento do Node </a>. Revise o Tutorial Express.</td>
</tr>
<tr>
<th scope="row">Objetivo:</th>
<td>Iniciar nosso website usando o "<em>Express Application Generator"</em>.</td>
</tr>
</tbody>
</table>
<h2 id="Visão_Geral">Visão Geral</h2>
<p>Nesse artigo mostraremos como criar a estrutura do website usando a ferramenta "<a href="https://expressjs.com/en/starter/generator.html">Express Application Generator</a> ". Neste caso, usaremos a ferramenta para criar o framework para nosso <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">website "LocalLibrary" </a>, tpara o qual adicionaremos mais tarde todo o outro código necessário para o site. O processo é extremamente simples, com apenas a requisição de invocar o "Generator" na linha de comando com um novo nome de projeto, e, se quiser, especificar o <em>template </em>do site e o gerador de CSS. </p>
<p><span style="line-height: 1.5;">As seguintes sessões mostrará como chamar o "Application Generator", e prover uma pequena explicação sobre as diferentes opções de CSS. Também aprenderemos como a estrutura do site é definida. No final, será mostrado como podemos rodar o site para ver se funciona.</span></p>
<div class="note">
<p><span style="line-height: 1.5;"><strong>Nota</strong>: O "<em>Express Application Generator"</em> não é o único gerador para as aplicações do Express, e o projeto gerado não é a única maneira viável de estruturar seus arquivos e diretórios. O site gerado, entretanto, tem um estrutura modular que é fácil de extender e ser entendida. Para aprender melhor sobre a aplicação do "<em>minimal</em> Express", veja <a href="https://expressjs.com/en/starter/hello-world.html">Exemplo"Hello world" </a>.</span></p>
</div>
<h2 id="Usando_o_Application_Generator">Usando o "Application Generator"</h2>
<p>Você já deve ter instalado o gerador como requisito.Como um lembrete rápido, você instala a ferramenta de gerador em todo o site usando o Gerenciador de pacotes NPM, como mostrado:</p>
<pre class="brush: bash"><code>npm install express-generator -g</code></pre>
<p>O gerador tem algumas opções que podem ser visualizadas usando o comando <code>--help</code> (or <code>-h</code>):</p>
<pre class="brush: bash">> express --help
Usage: express [options] [dir]
Options:
--version output the version number
-e, --ejs add ejs engine support
--pug add pug engine support
--hbs add handlebars engine support
-H, --hogan add hogan.js engine support
-v, --view <engine> add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
--no-view use static html instead of view engine
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
-h, --help output usage information
</pre>
<p>Você pode simplesmente especificar <code>express</code> para criar um projeto dentro do diretório atual usando <em>Jade</em> view e CSS simples (se você especificar um nome de diretório, o projeto será criado em uma subpasta com esse nome).</p>
<pre class="brush: bash"><code>express</code></pre>
<p>Também pode ser escolhido um "view" (<em>template)</em> usando<code>--view</code> e/ou um gerador de CSS usando <code>--css</code>.</p>
<div class="note">
<p><strong>Nota:</strong> As outras opções para escolher os mecanismos de modelo (e.g. <code>--hogan</code>, <code>--ejs</code>, <code>--hbs</code> etc.) são preteridas. Use <code>--view</code> (ou<code> -v</code>)!</p>
</div>
<h3 id="Qual_engine_de_view_devo_usar">Qual <em>engine</em> de "view" devo usar?</h3>
<p>The <em>Express Application Generator</em> allows you to configure a number of popular view/templating engines, including <a href="https://www.npmjs.com/package/ejs">EJS</a>, <a href="http://github.com/donpark/hbs">Hbs</a>, <a href="https://pugjs.org/api/getting-started.html">Pug</a> (Jade), <a href="https://www.npmjs.com/package/twig">Twig</a>, and <a href="https://www.npmjs.com/package/vash">Vash</a>, although it chooses Jade by default if you don't specify a view option. Express itself can also support a large number of other templating languages <a href="https://github.com/expressjs/express/wiki#template-engines">out of the box</a>.</p>
<div class="note">
<p><strong>Note:</strong> If you want to use a template engine that isn't supported by the generator then see <a href="https://expressjs.com/en/guide/using-template-engines.html">Using template engines with Express</a> (Express docs) and the documentation for your target view engine.</p>
</div>
<p>Generally speaking, you should select a templating engine that delivers all the functionality you need and allows you to be productive sooner — or in other words, in the same way that you choose any other component! Some of the things to consider when comparing template engines:</p>
<ul>
<li>Time to productivity — If your team already has experience with a templating language then it is likely they will be productive faster using that language. If not, then you should consider the relative learning curve for candidate templating engines.</li>
<li>Popularity and activity — Review the popularity of the engine and whether it has an active community. It is important to be able to get support for the engine when you have problems over the lifetime of the website.</li>
<li>Style — Some template engines use specific markup to indicate inserted content within "ordinary" HTML, while others construct the HTML using a different syntax (for example, using indentation and block names).</li>
<li>Performance/rendering time.</li>
<li>Features — you should consider whether the engines you look at have the following features available:
<ul>
<li>Layout inheritance: Allows you to define a base template and then "inherit" just the parts of it that you want to be different for a particular page. This is typically a better approach than building templates by including a number of required components or building a template from scratch each time.</li>
<li>"Include" support: Allows you to build up templates by including other templates.</li>
<li>Concise variable and loop control syntax.</li>
<li>Ability to filter variable values at template level (e.g. making variables upper-case, or formatting a date value).</li>
<li>Ability to generate output formats other than HTML (e.g. JSON or XML).</li>
<li>Support for asynchronous operations and streaming.</li>
<li>Can be used on the client as well as the server. If a templating engine can be used on the client this allows the possibility of serving data and having all or most of the rendering done client-side.</li>
</ul>
</li>
</ul>
<div class="note">
<p><strong>Tip:</strong> There are many resources on the Internet to help you compare the different options!</p>
</div>
<p>For this project, we'll use the <a href="https://pugjs.org/api/getting-started.html">Pug</a> templating engine (this is the recently-renamed Jade engine), as this is one of the most popular Express/JavaScript templating languages and is supported out of the box by the generator.</p>
<h3 id="What_CSS_stylesheet_engine_should_I_use">What CSS stylesheet engine should I use?</h3>
<p>The <em>Express Application Generator</em> allows you to create a project that is configured to use the most common CSS stylesheet engines: <a href="http://lesscss.org/">LESS</a>, <a href="http://sass-lang.com/">SASS</a>, <a href="http://compass-style.org/">Compass</a>, <a href="http://stylus-lang.com/">Stylus</a>.</p>
<div class="note">
<p><strong>Note: </strong>CSS has some limitations that make certain tasks difficult. CSS stylesheet engines allow you to use more powerful syntax for defining your CSS and then compile the definition into plain-old CSS for browsers to use.</p>
</div>
<p>As with templating engines, you should use the stylesheet engine that will allow your team to be most productive. For this project, we'll use the ordinary CSS (the default) as our CSS requirements are not sufficiently complicated to justify using anything else.</p>
<h3 id="What_database_should_I_use">What database should I use?</h3>
<p>The generated code doesn't use/include any databases. <em>Express</em> apps can use any <a href="https://expressjs.com/en/guide/database-integration.html">database mechanism</a> supported by <em>Node</em> (<em>Express</em> itself doesn't define any specific additional behavior/requirements for database management).</p>
<p>We'll discuss how to integrate with a database in a later article.</p>
<h2 id="Creating_the_project">Creating the project</h2>
<p>For the sample <em>Local Library</em> app we're going to build, we'll create a project named <em>express-locallibrary-tutorial </em>using the <em>Pug</em> template library and no CSS stylesheet engine.</p>
<p>First, navigate to where you want to create the project and then run the <em>Express Application Generator</em> in the command prompt as shown:</p>
<pre class="brush: bash">express express-locallibrary-tutorial --view=pug
</pre>
<p>The generator will create (and list) the project's files.</p>
<pre class="brush: bash"> create : express-locallibrary-tutorial\
create : express-locallibrary-tutorial\public\
create : express-locallibrary-tutorial\public\javascripts\
create : express-locallibrary-tutorial\public\images\
create : express-locallibrary-tutorial\public\stylesheets\
create : express-locallibrary-tutorial\public\stylesheets\style.css
create : express-locallibrary-tutorial\routes\
create : express-locallibrary-tutorial\routes\index.js
create : express-locallibrary-tutorial\routes\users.js
create : express-locallibrary-tutorial\views\
create : express-locallibrary-tutorial\views\error.pug
create : express-locallibrary-tutorial\views\index.pug
create : express-locallibrary-tutorial\views\layout.pug
create : express-locallibrary-tutorial\app.js
create : express-locallibrary-tutorial\package.json
create : express-locallibrary-tutorial\bin\
create : express-locallibrary-tutorial\bin\www
change directory:
> cd express-locallibrary-tutorial
install dependencies:
> npm install
run the app:
> SET DEBUG=express-locallibrary-tutorial:* & npm start</pre>
<p>At the end of the output, the generator provides instructions on how you install the dependencies (as listed in the <strong>package.json</strong> file) and then how to run the application (the instructions above are for Windows; on Linux/macOS they will be slightly different).</p>
<div class="blockIndicator note">
<p><strong>Note:</strong> When using Windows, the && and & assumes you are using the Command Prompt. If you are using the new default PowerShell terminal do not concatenate the commands with && and &. Instead set the DEBUG environment variable with $ENV:DEBUG = "express-locallibrary-tutorial:*";. The npm start can be followed by the npm start. </p>
</div>
<h2 id="Running_the_skeleton_website">Running the skeleton website</h2>
<p>At this point, we have a complete skeleton project. The website doesn't actually <em>do</em> very much yet, but it's worth running it to show how it works.</p>
<ol>
<li>First, install the dependencies (the <code>install</code> command will fetch all the dependency packages listed in the project's<strong> package.json</strong> file).
<pre class="brush: bash">cd express-locallibrary-tutorial
npm install</pre>
</li>
<li>Then run the application.
<ul>
<li>On Windows, use this command:
<pre class="brush: bash">SET DEBUG=express-locallibrary-tutorial:* & npm start</pre>
</li>
<li>On macOS or Linux, use this command:
<pre class="brush: bash">DEBUG=express-locallibrary-tutorial:* npm start
</pre>
</li>
</ul>
</li>
<li>Then load <a href="http://localhost:3000/">http://localhost:3000/</a> in your browser to access the app.</li>
</ol>
<p>You should see a browser page that looks like this:</p>
<p><img alt="Browser for default Express app generator website" src="https://mdn.mozillademos.org/files/14375/ExpressGeneratorSkeletonWebsite.png" style="display: block; height: 403px; margin: 0px auto; width: 576px;"></p>
<p>You have a working Express application, serving itself to <em>localhost:3000</em>.</p>
<div class="note">
<p><strong>Note:</strong> You could also start the app just using the <code>npm start</code> command. Specifying the DEBUG variable as shown enables console logging/debugging. For example, when you visit the above page you'll see debug output like this:</p>
<pre class="brush: bash">>SET DEBUG=express-locallibrary-tutorial:* & npm start
> express-locallibrary-tutorial@0.0.0 start D:\github\mdn\test\exprgen\express-locallibrary-tutorial
> node ./bin/www
express-locallibrary-tutorial:server Listening on port 3000 +0ms
GET / 304 490.296 ms - -
GET /stylesheets/style.css 200 4.886 ms - 111
</pre>
</div>
<h2 id="Enable_server_restart_on_file_changes">Enable server restart on file changes</h2>
<p>Any changes you make to your Express website are currently not visible until you restart the server. It quickly becomes very irritating to have to stop and restart your server every time you make a change, so it is worth taking the time to automate restarting the server when needed.</p>
<p>One of the easiest such tools for this purpose is <a href="https://github.com/remy/nodemon">nodemon</a>. This is usually installed globally (as it is a "tool"), but here we'll install and use it locally as a <em>developer dependency</em>, so that any developers working with the project get it automatically when they install the application. Use the following command in the root directory for the skeleton project:</p>
<pre class="brush: bash">npm install --save-dev nodemon</pre>
<p>If you still choose to install <a href="https://github.com/remy/nodemon">nodemon</a> globally to your machine, and not only to your project's <strong>package.json</strong> file:</p>
<pre class="brush: bash">npm install -g nodemon</pre>
<p>If you open your project's <strong>package.json</strong> file you'll now see a new section with this dependency:</p>
<pre class="brush: json"> "devDependencies": {
"nodemon": "^1.18.10"
}
</pre>
<p>Because the tool isn't installed globally we can't launch it from the command line (unless we add it to the path) but we can call it from an NPM script because NPM knows all about the installed packages. Find the the <code>scripts</code> section of your package.json. Initially, it will contain one line, which begins with <code>"start"</code>. Update it by putting a comma at the end of that line, and adding the <code>"devstart"</code> line seen below:</p>
<pre class="brush: json"> "scripts": {
"start": "node ./bin/www"<strong>,</strong>
<strong> "devstart": "nodemon ./bin/www"</strong>
},
</pre>
<p>We can now start the server in almost exactly the same way as previously, but with the <code>devstart</code> command specified:</p>
<ul>
<li>On Windows, use this command:
<pre class="brush: bash">SET DEBUG=express-locallibrary-tutorial:* & npm <strong>run devstart</strong></pre>
</li>
<li>On macOS or Linux, use this command:
<pre class="brush: bash">DEBUG=express-locallibrary-tutorial:* npm <strong>run devstart</strong>
</pre>
</li>
</ul>
<div class="note">
<p><strong>Note:</strong> Now if you edit any file in the project the server will restart (or you can restart it by typing <code>rs</code> on the command prompt at any time). You will still need to reload the browser to refresh the page.</p>
<p>We now have to call "<code>npm run <em><scriptname></em></code>" rather than just <code>npm start</code>, because "start" is actually an NPM command that is mapped to the named script. We could have replaced the command in the <em>start</em> script but we only want to use <em>nodemon</em> during development, so it makes sense to create a new script command.</p>
</div>
<h2 id="The_generated_project">The generated project</h2>
<p>Let's now take a look at the project we just created.</p>
<h3 id="Directory_structure">Directory structure</h3>
<p>The generated project, now that you have installed dependencies, has the following file structure (files are the items <strong>not</strong> prefixed with "/"). The <strong>package.json</strong> file defines the application dependencies and other information. It also defines a startup script that will call the application entry point, the JavaScript file <strong>/bin/www</strong>. This sets up some of the application error handling and then loads <strong>app.js</strong> to do the rest of the work. The app routes are stored in separate modules under the <strong>routes/</strong> directory. The templates are stored under the /<strong>views</strong> directory.</p>
<pre>/express-locallibrary-tutorial
<strong>app.js</strong>
/bin
<strong>www</strong>
<strong>package.json</strong>
<strong>package-lock.json</strong>
/node_modules
[about 6700 subdirectories and files]
/public
/images
/javascripts
/stylesheets
<strong>style.css</strong>
/routes
<strong>index.js</strong>
<strong>users.js</strong>
/views
<strong>error.pug</strong>
<strong>index.pug</strong>
<strong>layout.pug</strong>
</pre>
<p>The following sections describe the files in a little more detail.</p>
<h3 id="package.json">package.json</h3>
<p>The <strong>package.json </strong>file defines the application dependencies and other information:</p>
<pre class="brush: json">{
"name": "express-locallibrary-tutorial",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"morgan": "~1.9.0",
"pug": "2.0.0-beta11"
},
"devDependencies": {
"nodemon": "^1.18.10"
}
}
</pre>
<p>The dependencies include the <em>express</em> package and the package for our selected view engine (<em>pug</em>). In addition, we have the following packages that are useful in many web applications:</p>
<ul>
<li><a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a>: Used to parse the cookie header and populate <code>req.cookies</code> (essentially provides a convenient method for accessing cookie information).</li>
<li><a href="https://www.npmjs.com/package/debug">debug</a>: A tiny node debugging utility modeled after node core's debugging technique.</li>
<li><a href="https://www.npmjs.com/package/morgan">morgan</a>: An HTTP request logger middleware for node.</li>
<li><a href="https://www.npmjs.com/package/http-errors">http-errors</a>: Create HTTP errors where needed (for express error handling).</li>
</ul>
<p>The scripts section defines a "<em>start</em>" script, which is what we are invoking when we call <code>npm start</code> to start the server. From the script definition, you can see that this actually starts the JavaScript file <strong>./bin/www</strong> with <em>node</em>. It also defines a "<em>devstart</em>" script, which we invoke when calling <code>npm run devstart</code> instead. This starts the same <strong>./bin/www</strong> file, but with <em>nodemon</em> rather than <em>node</em>.</p>
<pre class="brush: json"> "scripts": {
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www"
},
</pre>
<h3 id="www_file">www file</h3>
<p>The file <strong>/bin/www</strong> is the application entry point! The very first thing this does is <code>require()</code> the "real" application entry point (<strong>app.js</strong>, in the project root) that sets up and returns the <code><a href="http://expressjs.com/en/api.html">express()</a></code> application object.</p>
<pre class="brush: js">#!/usr/bin/env node
/**
* Module dependencies.
*/
<strong>var app = require('../app');</strong>
</pre>
<div class="note">
<p><strong>Note:</strong> <code>require()</code> is a global node function that is used to import modules into the current file. Here we specify <strong>app.js</strong> module using a relative path and omitting the optional (.<strong>js</strong>) file extension.</p>
</div>
<p>The remainder of the code in this file sets up a node HTTP server with <code>app</code> set to a specific port (defined in an environment variable or 3000 if the variable isn't defined), and starts listening and reporting server errors and connections. For now you don't really need to know anything else about the code (everything in this file is "boilerplate"), but feel free to review it if you're interested.</p>
<h3 id="app.js">app.js</h3>
<p>This file creates an <code>express</code> application object (named <code>app</code>, by convention), sets up the application with various settings and middleware, and then exports the app from the module. The code below shows just the parts of the file that create and export the app object:</p>
<pre class="brush: js"><code>var express = require('express');
var app = express();
...
</code>module.exports = app;
</pre>
<p>Back in the <strong>www</strong> entry point file above, it is this <code>module.exports</code> object that is supplied to the caller when this file is imported.</p>
<p>Let's work through the <strong>app.js</strong> file in detail. First, we import some useful node libraries into the file using <code>require()</code>, including http-errors, <em>express</em>, <em>morgan</em> and <em>cookie-parser</em> that we previously downloaded for our application using NPM; and <em>path</em>, which is a core Node library for parsing file and directory paths.</p>
<pre class="brush: js">var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
</pre>
<p>Then we <code>require()</code> modules from our routes directory. These modules/files contain code for handling particular sets of related "routes" (URL paths). When we extend the skeleton application, for example to list all books in the library, we will add a new file for dealing with book-related routes.</p>
<pre class="brush: js">var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
</pre>
<div class="note">
<p><strong>Note:</strong> At this point, we have just <em>imported</em> the module; we haven't actually used its routes yet (this happens just a little bit further down the file).</p>
</div>
<p>Next, we create the <code>app</code> object using our imported <em>express</em> module, and then use it to set up the view (template) engine. There are two parts to setting up the engine. First, we set the '<code>views</code>' value to specify the folder where the templates will be stored (in this case the subfolder <strong>/views</strong>). Then we set the '<code>view engine</code>' value to specify the template library (in this case "pug").</p>
<pre class="brush: js">var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
</pre>
<p>The next set of functions call <code>app.use()</code> to add the <em>middleware</em> libraries into the request handling chain. In addition to the 3rd party libraries we imported previously, we use the <code>express.static</code> middleware to get <em>Express</em> to serve all the static files in the <strong>/public</strong> directory in the project root.</p>
<pre class="brush: js">app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
<strong>app.use(express.static(path.join(__dirname, 'public')));</strong>
</pre>
<p>Now that all the other middleware is set up, we add our (previously imported) route-handling code to the request handling chain. The imported code will define particular routes for the different <em>parts</em> of the site:</p>
<pre class="brush: js">app.use('/', indexRouter);
app.use('/users', usersRouter);
</pre>
<div class="note">
<p><strong>Note:</strong> The paths specified above ('/' and '<code>/users'</code>) are treated as a prefix to routes defined in the imported files. So for example, if the imported <strong>users</strong> module defines a route for <code>/profile</code>, you would access that route at <code>/users/profile</code>. We'll talk more about routes in a later article.</p>
</div>
<p id="error_handling">The last middleware in the file adds handler methods for errors and HTTP 404 responses.</p>
<pre class="brush: js">// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
</pre>
<p>The Express application object (app) is now fully configured. The last step is to add it to the module exports (this is what allows it to be imported by <strong>/bin/www</strong>).</p>
<pre class="brush: js">module.exports = app;</pre>
<h3 id="Routes">Routes</h3>
<p>The route file <strong>/routes/users.js</strong> is shown below (route files share a similar structure, so we don't need to also show <strong>index.js</strong>). First, it loads the <em>express</em> module and uses it to get an <code>express.Router</code> object. Then it specifies a route on that object and lastly exports the router from the module (this is what allows the file to be imported into <strong>app.js</strong>).</p>
<pre class="brush: js">var express = require('express');
var router = express.Router();
/* GET users listing. */
<strong>router.get('/', function(req, res, next) {
res.send('respond with a resource');</strong>
});
module.exports = router;
</pre>
<p>The route defines a callback that will be invoked whenever an HTTP <code>GET</code> request with the correct pattern is detected. The matching pattern is the route specified when the module is imported ('<code>/users</code>') plus whatever is defined in this file ('<code>/</code>'). In other words, this route will be used when an URL of <code>/users/</code> is received.</p>
<div class="note">
<p><strong>Tip:</strong> Try this out by running the server with node and visiting the URL in your browser: <a href="http://localhost:3000/users/">http://localhost:3000/users/</a>. You should see a message: 'respond with a resource'.</p>
</div>
<p>One thing of interest above is that the callback function has the third argument '<code>next</code>', and is hence a middleware function rather than a simple route callback. While the code doesn't currently use the <code>next</code> argument, it may be useful in the future if you want to add multiple route handlers to the <code>'/'</code> route path.</p>
<h3 id="Views_(templates)">Views (templates)</h3>
<p>The views (templates) are stored in the <strong>/views</strong> directory (as specified in <strong>app.js</strong>) and are given the file extension <strong>.pug</strong>. The method <code><a href="http://expressjs.com/en/4x/api.html#res.render">Response.render()</a></code> is used to render a specified template along with the values of named variables passed in an object, and then send the result as a response. In the code below from <strong>/routes/index.js</strong> you can see how that route renders a response using the template "index" passing the template variable "title".</p>
<pre class="brush: js">/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
</pre>
<p>The corresponding template for the above route is given below (<strong>index.pug</strong>). We'll talk more about the syntax later. All you need to know for now is that the <code>title</code> variable (with value <code>'Express'</code>) is inserted where specified in the template.</p>
<pre>extends layout
block content
h1= title
p Welcome to #{title}
</pre>
<h2 id="Challenge_yourself">Challenge yourself</h2>
<p>Create a new route in <strong>/routes/users.js</strong> that will display the text "<em>You're so cool"</em> at URL <code>/users/cool/</code>. Test it by running the server and visiting <a href="http://localhost:3000/users/cool/">http://localhost:3000/users/cool/</a> in your browser</p>
<ul>
</ul>
<h2 id="Summary">Summary</h2>
<p>You have now created a skeleton website project for the <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Local Library</a> and verified that it runs using <em>node</em>. Most importantly, you also understand how the project is structured, so you have a good idea where we need to make changes to add routes and views for our local library.</p>
<p>Next, we'll start modifying the skeleton so that it works as a library website.</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="https://expressjs.com/en/starter/generator.html">Express application generator</a> (Express docs)</li>
<li><a href="https://expressjs.com/en/guide/using-template-engines.html">Using template engines with Express</a> (Express docs)</li>
</ul>
<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}</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>
|