© Jörg Krause 2017

Jörg Krause, Programming Web Applications with Node, Express and Pug , 10.1007/978-1-4842-2511-0_5

5. Introduction to Express

Jörg Krause

(1)Berlin, Germany

Express is the middleware component of a Node application. Thus, the switching layer between the client and the back end is meant with its persistence functions. The core task is the routing.

Installation

A condition for Express is a functioning Node environment. If this is available, you can create your first application. The operational sequence shown here makes Express available; however, you must provide the actual infrastructure manually. In the section ** application structure **, you find information about how the express generator can be used in order to simplify this.

First, a folder for the application is created:

1   mkdir SimpleApp
2   cd SimpleApp

With “nmp init”, you then produce a package.json file. Thus, the application and its dependence are described.

1   npm init

The information for the description file is queried in the dialogue. In most cases it is to be transferred to order the standards. Thus, simply press ENTER several times, except for the option “entry point.” Here you enter the following:

1   entry point: app.js

This determines that the starting file, thus the beginning of the application, is app.js. You can naturally select each name.

Now Express is being installed and received in the list of dependence (option “–save”). If necessary, add the option -g to make Express globally available. That is meaningful, if you plan on developing further proects with Node.

1   $ npm install express --save
A435076_1_En_5_Fig1_HTML.jpg
Figure 5-1. Interactive installation (Ubuntu)

Application structure

Express supplies a finished application structure. With the installation, not only is the Express module available, but also the finished folder structure can be provided with only one instruction.

However, you do not have to use this. It is quite possible to provide an application very easily by only constructing one file.

With the installation in the previous section, it was said during the initialization that the starting file is named app.js. However, this could now look as follows:

 1   var express = require('express');
 2   var app = express();
 3
 4   app.get('/', function (req, res) {
 5     res.send('Hallo Express!');
 6   });
 7
 8   var server = app.listen(3000, function () {
 9     var host = server.address().address;
10     var port = server.address().port;
11
12     console.log('I listen on http://%s:%s', host, port);
13   });

Here Express is first merged and provides with the constructor call an application App. Then a route is specified, the master route “/”. All other calls lead to an HTTP error 404 (not found). Then the terminal is determined, here the port 3000 on the local system (line 8). Now if an HTTP request arrives, the function of the suitable route is implemented. In the example the text “hello express!” is spent afterwards. HTML does not return this script. Everything must be settled separately. However, it already concerns a correct HTML communication.

The express generator

For producing an application, the express generator can be used. This is available as a further NPM package.

1   $ npm install express-generator -g

In addition, the generator has some options, but also produces a meaningful environment without further details.

Table 5-1. Options of the express generators

Option

Meaning

–version

Version

–pug

Pug Engine support

-e, –ejs

EJS-Engine (see www.embeddedjs.com )

-hbs

Handlebars Engine

-H, –hogan

Hogan Engine ( www.hogan.js )

-c, –css [CS]

CSS Precompiler

-f, –force

Force files in nonempty folders

The standard Template engine is Jade.

The CSS Precompiler can be one of the following (name and, in parentheses, the one which can be used as option):

  • LESS (less)

  • Stylus (stylus)

  • Compass (compass)

  • SASS (sass)

Without information, simple CSS is expected.

LESS or SASS

In this work, LESS ( http://lesscss.org ) is used. That is, in principle irrelevant. If you already have a favorite, use that one. If both are new, then you might become somewhat happier with LESS at the beginning, since it is simpler and more common (more sources for learning and less expenditure). However, most professionals use SASS instead ( http://sass-lang.com ).

The generator also produces the master directory of the application, so that you should begin in the superordinate listing:

1   express PortalApp                          
2   cd PortalApp
3   npm install

With this instruction sequence, an application with the name *PortalApp is provided in the folder PortalApp. Now the application is started in the Debug mode:

set DEBUG=PortalApp & npm start

The standard address is http://localhost:3000. The web server is based on Node and further settings at the operating system are not necessary. You must neither have ISS nor Apache nor any other server available for this. It just functions.

A435076_1_En_5_Figa_HTML.jpg Windows

Under Windows Sockets for HTTP, communication from the Kernel driver http.sys are made available. Node registers the Port 3000 there. That succeeds only if the port is free. Thus it can happen that Node collides with a likewise installed and active IIS or Apache web server.

A435076_1_En_5_Figb_HTML.jpg Only for the start

It is smart to begin with the structure produced by the generator and start with further modifications at a later time if the need for it is there.

The following structure develops according to standard:

A435076_1_En_5_Fig2_HTML.jpg
Figure 5-2. Structure, which the generator puts on

Routing in Node application

The Routing manufactures a connection between a URL and an implementing instance (method or module). Every time an application delivers more than one site, routing comes into play. That also applies to Single Page Applications (SPA ). Because with the conditions of today’s browsers you are well advised if everything is pressed into only one site. The rough raster of the application is waved better in several server page modules, which can be implemented well for their part in each case as SPA.

This has a completely different meaning if no SPA is provided. Then it’s practically about steering the distribution of each single page. Apart from the sites themselves, the routing then also deals with the parameters, which are provided as part of the URL and which must be supplied with implementing methods.

Routing in Express

If more sites of an application are added, more routes are needed. In addition, serves the express router. This will be more comprehensively treated later on. However, routes do not only deliver finished sites. If a part of the application in the Single Page Style (SPA) is developed, use Express in order to provide the routes for their client page programmed calls. For example, this can take place with AngularJS. Express then illustrates a RESTful back end for AngularJS.

A435076_1_En_5_Figc_HTML.jpg RESTful With RESTful, a complete interface based on REST is used. Thus all typical procedures become regarding resources—reading, changing, producing and deleting—and completed over the suitable HTTP instructions.

Only the combination of server page technology and client page elements constitutes a modern Web application.

The Express Router

The Express Router is a pure routing module without many extras.

There is no explicit support of Views or pre-defined settings. However, there are rudimentary APIs like use(), get(), param() and route(). There are different possibilities of using the router. The use of get() is thereby only one variant. The following example application uses these and some other techniques. At the end of the text you’ll find a complete description of the entire API.

A435076_1_En_5_Figd_HTML.jpg API

API stands for Application Programming Interfaceand designates a clearly defined interface, over which applications can access functions of a library or a framework.

An example application

The example application has some techniques, which can be used meaningfully in practice:

  • simple routes, e.g., to the homepage

  • sectional routes, e.g., for the Admin range

  • use of the middleware for the logging

  • use of parameters

  • use of the middleware for the validation of parameters

  • implementation of a registration function with distinction of GET and POST

  • validation of a parameter for a certain route

Now, the term middleware has already been used several times. But why is it called that and where is the connection with Express?

Middleware – the mediator layer

The name middleware is splendidly selected. The functions placed here are implemented after the arrival of the request by the client and before the forwarding of an answer. Thus, they have relevant influence on the processing of the request. An application is the logging of requests. These take place in the middleware, without consideration for the function of the other components. They are transparent and in the background.

A435076_1_En_5_Fige_HTML.jpg Middleware

Middleware (service layer or intermediate’s application) designates application-neutral programs, which mediate between applications in order to hide the complexity of these applications and their infrastructure in computer science. One can view middleware as a kind distribution platform. A middleware supports communication between processes. In Express, the middleware is the meditator between request and answer.

Basic routes

The route to the home page was already defined. These, like all other routes, are defined in the file app.js. This file is in the best place in the project, as long as the number of routes is visible. Since with a Single Page Application (SPA ) only the rough raster of the routes is used on the sever, this is correct. AngularJS then deals with the routes on the client site and regulates the inquiry-specific partial sighting by means of parameters.

Defined routes react to specific paths and HTTP verbs such as GET, POST, PUT/PATCH or DELETE. This functions—with or without RESTful actions—as long as only one handful of routes is needed.

Now it can occur that nevertheless more complex routes become necessary. Complex web sites have not only a range, but also back-end functions, administration ranges, import and export, reporting, and much more. Each range can have innumerable routes.

A435076_1_En_5_Figf_HTML.jpg Simplification of the examples

The following examples only send simple data back instead of complete Views, in order to arrange the code more readably. Replace the returns through appropriate View calls in practice. The starting point is the function express.Router().

The function express.Router( ) is a kind of mini-application. You thereby produce an instance of the router and define for this instance some routes.

Listing 5-1. app.js
 1   // Die Applikationsinstanz wird gebildet            
 2   var express = require('express');
 3   var app = express();
 4
 5   // Eine neue Instanz des Routers wird erstellt
 6   var adminRouter = express.Router();
 7
 8   // The Admin-Site (http://localhost:3000/admin)
 9   adminRouter.get('/', function(req, res) {
10     res.send('Homepage of admin area!');
11   });
12
13   // The User-Site (http://localhost:3000/admin/users)
14   adminRouter.get('/users', function(req, res) {
15     res.send('show all users!');
16   });
17
18   // The article-Seite (http://localhost:3000/admin/article)
19   adminRouter.get('/article', function(req, res) {
20     res.send('Show all articles!');
21   });
22
23   // Assign routes to application
24   app.use('/admin', adminRouter);
25
26   // Der Server
27   var server = app.listen(3000, function() {
28     console.log('Server started');
29   });

The routes are basically provided in an isolated manner and then assigned as a group of the application. Thereby, the paths are added.

The master path is determined by the method “use.” The instruction could also look as follows:

app.use('/app', router)

Such mini-applications can be assigned several times and thus can win you some clarity over things. Logically separate ranges, as for example Views and REST API, can be kept apart now and can cleanly be separated in the source code.

The Router Middleware (router.use())

The middleware generally intervenes before the actual processing.

This is meaningful for a set of tasks:

  • authentication

  • authorization

  • logging

  • cache

A435076_1_En_5_Figg_HTML.jpg Infrastructure use!

Above all, tasks like the authentication should never take place in the password, but take off from the infrastructure.

The definition of the functions takes place in the same order in which it is supposed to be used later on. The facility takes place after the production of the application before assigning the routes. The following example shows how all requests on the console are spent.

1   // Funktion, die auf jede Anfrage reagiert            
2   adminRouter.use(function(req, res, next) {
3     // Konsolenausgabe
4     console.log(req.method, req.url);
5     // Weiter mit der regulären Verarbeitung
6     next();
7   });

The call of the method next() is crucial. Therewith, Express is being told that the method was processed and the regular processing can continue. adminRouter.use() defines the middleware function. Actual functionality is to be separately implemented and thus pure JavaScript.

The sequence of the registration of the functions also determines the order of the processing. After the route there is no place for the middleware functions, because the processing of the request ends there with the sending of the data.

Structure Routes

So far it was already shown how routes can be assigned in sections.

The approach is similar with most projects. The home page with its most important link is a range, the administration another. An API—RESTful or not—should always be led separately. Thus, you have enough clearance in order not to lose the overwie with extensions.

The definition of the ranges then looks like this:

1   app.use('/', basicRoutes);
2   app.use('/admin', adminRoutes);
3   app.use('/api', apiRoutes);

Routes with Parameters (/hello/:id)

The call of a site alone is usually not sufficient. If data from databases is called up, parameters must be transferred. The structure of the URL is almost arbitrary. However, they must consider the borders of HTTP. A URL is limited on 2000 indications. In addition, a complex URL makes you want to play with it, as it’s clearly visible and easy to manipulate. The more complex the URL, the more highly is the expenditure for the validation of the parameters.

If you call data up from databases, it offers to limit the primary key for all calls. That leads the data in the business logic to it (from connected tables or documents); thus, they’ll possibly be loaded again. In delivering such requests, databases are very good and the simplification with the organization of the server code is nearly never more valuable. Always call their primary parameter id.

In the description of the route, parameters are introduced with a colon:

1   adminRouter.get('/users/:id', function(req, res) {
2     res.send('Benutzer-ID: ' + req.params.id + '!');
3   });

The router recognizes this and transfers the values into an object with the name params, which is part of the requirement object req.

There, the parameters are available as features. The URL for this example looks as follows:

http://localhost:3000/admin/users/123

The path section admin was defined in the router. The specific path specifies user and 123 to the feature id to hand over. The colon serves the recognition and is not part of the path.

Because of the high susceptibility for manupulations, parameters must always be validated. Here again the middleware layer comes into play. It makes a method called param() available, to which the parameters are handed over before they are supplied to the processing.

Router Middleware for Parameters (.param)

Parameters must always be validated by high susceptibility for manipulations. Here again the middleware layer comes into play. It makes a method called param() , to which the parameters are handed over, before they are supplied to the processing.

The following example shows how the parameter id is checked:

Listing 5-2. param_sample.js
 1   adminRouter.param('id', function(req, res, next, name) {
 2     console.log('Validierung für ID ' + id);
 3     var id = Number(req.params.id);
 4     if (!id){
 5       // Fehlerbehandlung
 6     } else {
 7       // Ablage des geprüften Wertes
 8       req.id = id;
 9       // Weiter mit Verarbeitung
10       next();
11     }
12   });
13
14   adminRouter.get('/users/:id', function(req, res) {
15     res.send('ID: ' + req.id + '!');
16   });

A valid URL is here:

http://localhost:3000/admin/users/123

How the error handling looks here depends on the setting of tasks. A web site for (human) users requires reliably different reactions than a RESTful API, which must possibly react to technical errors.

Several Routes (app.route())

The function app.route() is a direct call of the router and corresponds to the call express.Router(). However, the function has in addition the possibility to create more routes in one step and to provide several actions over only one route. The latter avoids that with hundreds of actions. Likewise, many routes must be provided.

In the following example, a /login route is defined. To these react two methods: once the Verb GET is evaluated, once POST.

Listing 5-3. login_sample.js
1   app.route('/login')
2      .get(function(req, res) {
3         res.send('Das Anmeldeformular.');
4      })
5      .post(function(req, res) {
6         console.log('Anmelden');
7         res.send('Anmeldung verarbeitet!');
8      });

app is in this example the central application object and the definition usually takes place in the app.js file.

The approach is typical for all kinds of forms. If the page in the browser with http://localhost:3000/login is called, the browser produces a GET request. The user sees the form and fills it out. It sends it then with the transmission button (submit). The browser now provides a POST request and adds the form data.

A435076_1_En_5_Figh_HTML.jpg Where is the HTML?

In the example, the necessary HTML is not shown in order to keep the listing small. Simply write the standard form with HTML. There are no features for the processing with express.

One may now speak of the actions of a route. In the last example there were two actions. A RESTful API could react to further Verbs with the same route.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.134.17