ExpressJS Installation and Routing Guide
ExpressJS Installation and Routing Guide
2 - Installation of ExpressJS
After creating a specific folder, we execute the following two commands in it.
file :
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.
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();
$ 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]
These two routes are placed between the call of the ExpressJS module (require…) and the listening of
server ( listen ... ).
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]
[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:
On the server, the image is located in the public folder which has been previously declared at
means of an [Link].
[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'));
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]")
p
Contact me
The whole gives us a complete html file that is sent to the client.
doctype html
html
head
block title
title Default title
link(rel="stylesheet", href="[Link]")
script(src="[Link]")
body
block content
extends ./[Link]
block title
title= titrePage
block content
h1= titreH1
a short text
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:
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:
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]('/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:
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](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';
consturlDb ='mongodb://localhost:27017';
constnameDb ='blog';
const urlConnect = '8080';
[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';
varexpress = require('express');
varapp = express();
[Link]('view engine', 'pug');
[Link]('views','pugFiles');
vardbInterface =require('./db');
const urlConnect = '8080';
[Link](urlConnect,function(){
- The server is available on port 8080
});