0% found this document useful (0 votes)
4 views13 pages

ExpressJS Installation and Routing Guide

The document provides a comprehensive guide on ExpressJS, a lightweight Node.js framework for web application development, covering its installation, routing, middleware, and static file management. It also explains the use of Pug as a templating engine, session management, error handling, and database connectivity. Key features include managing GET and POST requests, using middleware functions, and organizing application structure for efficient development.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

ExpressJS Installation and Routing Guide

The document provides a comprehensive guide on ExpressJS, a lightweight Node.js framework for web application development, covering its installation, routing, middleware, and static file management. It also explains the use of Pug as a templating engine, session management, error handling, and database connectivity. Key features include managing GET and POST requests, using middleware functions, and organizing application structure for efficient development.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ExpressJS

A - Discovery and Installation


1 - ExpressJS: presentation and key features
operating principles
Express JS is a lightweight [Link] framework that offers
many functions to simplify the creation of a website. Express JS makes it easier
the organization of the application through several concepts:

guide in managing the request and the response


stack of middlewares
routing
templates

2 - Installation of ExpressJS
After creating a specific folder, we execute the following two commands in it.
file :

a) Prerequisite: creation of a JSON package


$ npm init

This is about creating a JSON file ([Link]) containing a description of the application
Express JS créée (nom, version, fichier de départ …). L'ensemble des spécifications sont
data in the npm documentation.

b) Installation of the ExpressJS module


$ npm install express

This command will install the Express module in our project and add its mention in the
[Link] file as a dependency.
Thus, it is possible to deploy a completed project, even if the modules are not present, in
executing the following command at the root folder of the project (the [Link] file
must be present)
$ npm install

3 - First display
After writing this code:

varexpress =require('express');
varapp = express();

[Link]('/', function(req, res) {


Hello everyone!
});

varserver = [Link](8080, function() {


var addressHotel = [Link]().address;
varportListen = [Link]().port;

[Link]('The application is available at the address


[Link]
});

let's execute it:

$ node [Link]

After entering localhost:8080 in the address bar of our browser, it displays "
Hello everyone.
B - The management of roads and
fichiers statiques
1 - Managing the different routes
Each time a request is sent to the server, it is processed by it as a route.
Here are two different routes:

[Link]
[Link]

The first is managed by ExpressJS in the following way:

[Link]('/', function(req, res) {


Hello
});

and the second one like this:

[Link]('/informations', function(req, res) {


Additional information
});

These two routes are placed between the call of the ExpressJS module (require…) and the listening of
server ( listen ... ).

2 - Send static files to


client

a) General case
The web application allows generating HTML files based on the requests made to it.
sent; but also to provide static files stored on the server such as
images, CSS or JavaScript for example.
Express allows for simplifying the writing of URLs for these files by storing them all in a
parent file.
To do this, one must use a middleware function (see below for this concept) by writing
:

[Link]([Link]('public'));

You can now store all your files in the public folder, located at the root of your
application, and write the URLs as follows:
[Link]
[Link]
[Link]
[Link]
[Link]

You can create multiple static folders:

[Link]([Link]('public'));
[Link]([Link]('files'));

Express will successively search your files in the different specified static folders.
This allows us, for example, to send an image tag to the client:

[Link]('/image', function(req, res) {


[Link]('<img src="public/[Link]">');
});

On the server, the image is located in the public folder which has been previously declared at
means of an [Link].

b) The HTML files


For now, we are sending a string using the send method of the object.
response provided by Express as the second argument of the callback function.
It is also possible to send an HTML document saved on the server. This file is
stored in a folder that will be declared by an [Link] (files in the example below)
Then, we can write on a route:

[Link]('/page',function(req,res){
[Link]('[Link]', {root: 'files'});
});
C - A template engine: Pug
1 - Basic principle
Pug is a templating language. It allows for separating the code that generates the display from the rest.
JavaScript code. You must use the syntax of the language.
We insert the following code into the JavaScript file

varexpress =require('express');
varapp = express();

Defines the base folder for static files (css, images, js,
[Link]('/static', [Link]('files'));

allows the use of Pug


[Link]('view engine','pug');

redefine the folder receiving .pug files (default: views)


[Link]('views', 'mestemplates');

//base path of my application:


[Link]('/', function(req, res) {
allows the rendering of the [Link] file which produces an html sent afterwards to
[Link]('index',{title:'Titre de la page',
message :'Du texte dans la page'});
});

We create an [Link] file in the mestemplates folder.

doctype html
head
title= title
body
h1= message

2 - Inclusion
In our web pages, part of the structure is common (header, menu …). It is therefore
preferable to separate these common areas from the rest. Let's take, first of all, a file
[Link]

doctype html
html
include ./includes/[Link]
body
h1= titreH1
A short text
include ./includes/[Link]
We then use the [Link] and [Link] files located in the includes folder itself.
located in the mestemplates folder.
The head file:

head
title= titrePage
script(src='[Link]')
link(rel="stylesheet", href="[Link]")

The file foot:

p
Contact me

The whole gives us a complete html file that is sent to the client.

3 - The inheritance (use of a layout)


Another code separation technique involves using a Layout. First of all,
let's take the file [Link]

doctype html
html
head
block title
title Default title
link(rel="stylesheet", href="[Link]")
script(src="[Link]")
body
block content

If we use the [Link] file below, we get a complete page.

extends ./[Link]

block title
title= titrePage

block content
h1= titreH1
a short text

Each .pug file called will use the layout.


D - Improvements
1 - Management of values using the method
GET
We can pass values in the URL and retrieve them on the server side. There are two ways.
to do.

a) [Link]
We use the following address for the request:[Link]
We can set up the following route to retrieve the values of thing and widget:

[Link]('/infos/:one/:two', function(req, res) {


[Link]([Link]); // prints thing
[Link]([Link]); //affiche machin
});

b) [Link]
We use the following address for the request:[Link]
r=chose&t=bidule.
We can set up the following route to retrieve the values thing and gadget:

[Link]('/question', function(req, res)) {


[Link]([Link].r); //displays something
[Link]([Link].t); // displays thing
}

2 - The middleware
Express is a lightweight web library that facilitates the construction of routes and uses functions.
middleware. Une demande expresse est, avant tout, une série d'appels de middleware.
Middleware is a function that will be called between the request and the response to provide
additional possibilities to our code.
Let's take the following code:

[Link](function(req,res,next){
[Link]('Time:', [Link]());
next();
});

At each request, the time will be displayed in the console. You notice that the function
Middleware is based on the [Link]() function. A function is given as an argument.
Among the most common middleware with Express, we find the definition of directories.
static, the use of a specific folder for the template, the handling of POST requests
or the management of sessions.
3 - Management of values with the method
POST
POST requests require special handling to process the values
sent. Here is the central part of the pug template to generate a form in html:
Let's take the following form:

form(action='response' method='post')
input(type='text' name='texte')
input(type='submit' value='Send')

To properly handle the data sent in the requests, we will use the
body-parser module which gives us the following code:

varexpress = require('express');
varapp = express();
var bodyParser = require('body-parser');
Shipping support
[Link]([Link]({
extended: false
}));

[Link]('view engine', 'pug');

[Link]('/reponse',function(req,res){
[Link]('reponse',{ titrePage:'Réponse du formualaire',
titreH1:'Une page de réponse',reponse:[Link]});
});

We notice that the text field of the form is retrieved at the end of line 12.
([Link]).
Finally, here is the central part of the response display template:

h1= titreH1
The response of the form is:
p #{response}

4 - Error Management
By default, [Link] does not generate errors. Therefore, we need to send a page with a...
404 head when the requested URL does not match any page of the site. In the following code,
located after all other routes, we add the 404 header before rendering the
Page 404 created elsewhere.

[Link](function(req,res,next){
[Link](404).render('404',{ titrePage:'Erreur',titreH1:'Des erreurs
});
Error 404 is not the only one present. For example, there is error 503 if the server is not working.
not correctly as well as the 403 error for protected content.
Let's take this excerpt from a road:

[Link]('/request', function(req, res, next) {



if (err) {
[Link]('503');
next();
return;
}

});

We must not forget to provide the next argument for each route. Thus, we arrive at the
middleware below located after all the routes:

[Link](function(req,res,next){
switch([Link]){
case403
[Link]('403',{ title:'Accès interdit !'});
break;
case503:
[Link]('503',{ title:'Problème'});
break;
default:
[Link](404).render('404',{ title:'Page inconnue'});
}
});

The test is done on the error code (statusCode) present in the res object to display a page.
different depending on the type of error.

5 - The sessions
A session is a defined period during which a client is in communication with a
server that performs operations for this individually identified client. This
identification allows restricting the use of a part of the site to certain individuals,
record personal data ...
We need to use two modules here: cookie-parser and express-session. Let's take the code
following:
varexpress =require('express');
var cookieParser = require('cookie-parser');
varsession =require('express-session');

varapp = express();
varsess
[Link](cookieParser())
[Link](session({
secret:'123456789SECRET',
saveUninitialized : false,
resave: false
}));

[Link]('view engine','pug');
[Link]('/static',[Link]('files'));

[Link]('/', function(req, res) {


sess = [Link];
if ([Link]) {
[Link]++;
} else {
[Link] =1;
}
[Link]('index',{titre :'accueil',
nombre :[Link]});
});

[Link](8080,function(){
listening on port 8008
});

The following Pug template allows the user to see how many times they have viewed the page:

doctype html
head
title= titre
body
Homepage
A text
You have viewed this page #{number} times.
E - Connection to the database
data
1 - Principe
In the following code, we connect to the database. If this connection does not return
pas d'erreur, le serveur se met en écoute et l'objet lié à la base de données est disponible pour
to be used on each route.

varexpress =require('express');
varapp = express();
varMongoClient = require('mongodb').MongoClient;
varmongoClient;
[Link]('view engine','pug');
[Link]('views','pugFiles');

consturlDb ='mongodb://localhost:27017';
constnameDb ='blog';
consturlConnect ='8080';

[Link]('/', function(req, res, next) {


var collection = [Link]('articles');
[Link]().sort({date:-1}).limit(10).toArray(function(err,data){
[Link]('index',{ title:'Bonjour',h1:'Une liste',liste: data})
});
});

[Link](urlDb, function(err, client) {


if (err) {
return;
}
mongoClient =[Link](nameDb);
[Link](urlConnect, function() {
- The server is available on port 8080
});
});

2 - Securing the connection


We are not sure that the connection will be available constantly. We need to
So establish the connection in each route and close the connection at the end of the route.
varexpress = require('express');
varapp = express();
varMongoClient = require('mongodb').MongoClient;
varmaDb;
[Link]('view engine', 'pug');
[Link]('views','pugFiles');

consturlDb ='mongodb://localhost:27017';
constnameDb ='blog';
const urlConnect = '8080';

[Link]('/', function(req, res, next) {


[Link](urlDb,function(err,client){
if (err) {
[Link](503);
next();
return;
}
varinstance = [Link](nameDb);
varcollection = [Link]('articles');
[Link]().sort({date:-1}).limit(10).toArray(function(err,data){
[Link]();
[Link]('index',{ title:'Bonjour',h1:'Une liste',liste: data})
});
});
});

[Link](urlConnect,function(){
- The server is available on port 8080
});
});
3 - Factorization of the connection
It would be wiser to group the connection code into a module ([Link]). For example
:

varurlDb ='mongodb://localhost:27017';
varnameDb ='blog';

[Link] = function(req, res, next, cb) {


if ([Link] && [Link]()) {
varinstance =[Link]([Link]);
cb(instance);
} else {
[Link](urlDb, function(err, client) {
[Link] = client;
if (err) {
[Link](503);
next();
return;
}
varinstance =[Link](nameDb);
cb(instance)
});
}
});

Our main file will then be as follows:

varexpress = require('express');
varapp = express();
[Link]('view engine', 'pug');
[Link]('views','pugFiles');

vardbInterface =require('./db');
const urlConnect = '8080';

[Link]('/', function(req, res, next) {


[Link](req,res,next,function(db){
varcollection = [Link]('articles');
[Link]().sort({date:-1}).limit(10).toArray(function(err,data){
[Link]('index',{ title:'Bonjour',h1:'Une liste',liste: data})
});
})
});

[Link](urlConnect,function(){
- The server is available on port 8080
});

You might also like