Technologies Web Backend – Série 2 [Link] & Express.
js
Université Sidi Mohamed Ben Abdellah
École Nationale des Sciences Appliquées de Fès
Filière ILIA / Semestre 2 – Année universitaire 2025–2026
CORRECTION – Technologies Web Backend
Série 2 : [Link] et [Link]
1 1 Exercice
1 – Serveur HTTP retournant du JSON
Objectif
Créer un serveur HTTP avec le module natif http qui retourne un objet étudiant au format
JSON sur le port 8000.
Fichier [Link]
1 const http = require ( ’ http ’) ;
2
3 // Donnees de l ’ etudiant
4 const student = {
5 nom : " Alami " ,
6 prenom : " Ahmed " ,
7 age : 23
8 };
9
10 // Creation du serveur HTTP
11 const server = http . createServer (( req , res ) = > {
12 res . writeHead (200 , { ’ Content - Type ’: ’ application / json ’ }) ;
13 res . end ( JSON . stringify ( student ) ) ;
14 }) ;
15
16 // Ecoute sur le port 8000
17 server . listen (8000 , () = > {
18 console . log ( ’ Serveur demarre sur http :// localhost :8000 ’) ;
19 }) ;
Listing 1 – Exercice 1 – [Link]
Test : Ouvrir [Link] dans un navigateur ou avec curl :
node server . js
curl http :// localhost :8000
# = > {" nom ":" Alami " ," prenom ":" Ahmed " ," age ":23}
1
Technologies Web Backend – Série 2 [Link] & [Link]
2 1 Exercice
2 – Module fs (système de fichiers)
Objectif
Manipuler des fichiers avec le module natif fs et servir un fichier HTML depuis un serveur
[Link].
1 const fs = require ( ’ fs ’) ;
2 const http = require ( ’ http ’) ;
3 const path = require ( ’ path ’) ;
4
5 // 1. Creer et ecrire dans message . txt
6 fs . writeFileSync ( ’ message . txt ’ ,
7 ’ Bonjour , bienvenue dans le module fs de Node . js ! ’) ;
8
9 // 2. Lire et afficher le contenu
10 const contenu = fs . readFileSync ( ’ message . txt ’ , ’ utf8 ’) ;
11 console . log ( ’ Contenu : ’ , contenu ) ;
12
13 // 3. Ajouter une ligne a la fin
14 fs . appendFileSync ( ’ message . txt ’ ,
15 ’\ nCette ligne a ete ajoutee a la suite . ’) ;
16
17 // 4. Supprimer le fichier
18 fs . unlinkSync ( ’ message . txt ’) ;
19 console . log ( ’ Fichier message . txt supprime . ’) ;
20
21 // 5. Creer index . html
22 const htmlContent = ‘ <! DOCTYPE html >
23 < html lang =" fr " >
24 < head > < meta charset =" UTF -8" > < title > Accueil </ title > </ head >
25 < body > < h1 > Bienvenue sur mon serveur Node . js ! </ h1 > </ body >
26 </ html > ‘;
27
28 fs . writeFileSync ( ’ index . html ’ , htmlContent ) ;
29
30 // 6. Serveur qui sert index . html
31 const server = http . createServer (( req , res ) = > {
32 const filePath = path . join ( __dirname , ’ index . html ’) ;
33 fs . readFile ( filePath , ( err , data ) = > {
34 if ( err ) {
35 res . writeHead (500) ;
36 res . end ( ’ Erreur interne du serveur ’) ;
37 return ;
38 }
39 res . writeHead (200 , { ’ Content - Type ’: ’ text / html ’ }) ;
40 res . end ( data ) ;
41 }) ;
42 }) ;
43
44 server . listen (8000 , () = > {
45 console . log ( ’ Serveur demarre sur http :// localhost :8000 ’) ;
2
Technologies Web Backend – Série 2 [Link] & [Link]
46 }) ;
Listing 2 – Exercice 2 – fs_demo.js
3 1 Exercice
3 – Routage multi-pages avec http
Objectif
Créer trois pages HTML ([Link], [Link], [Link]) et les servir selon
l’URL demandée.
1 const http = require ( ’ http ’) ;
2 const fs = require ( ’ fs ’) ;
3 const path = require ( ’ path ’) ;
4
5 const server = http . createServer (( req , res ) = > {
6 let filePath ;
7
8 switch ( req . url ) {
9 case ’/ ’:
10 filePath = path . join ( __dirname , ’ index . html ’) ;
11 break ;
12 case ’/ about ’:
13 filePath = path . join ( __dirname , ’ about . html ’) ;
14 break ;
15 case ’/ contact ’:
16 filePath = path . join ( __dirname , ’ contact . html ’) ;
17 break ;
18 default :
19 res . writeHead (404 , { ’ Content - Type ’: ’ text / html ’ }) ;
20 res . end ( ’ <h1 >404 -- Page non trouvee </ h1 > ’) ;
21 return ;
22 }
23
24 fs . readFile ( filePath , ( err , data ) = > {
25 if ( err ) {
26 res . writeHead (500) ;
27 res . end ( ’ Erreur interne ’) ;
28 return ;
29 }
30 res . writeHead (200 , { ’ Content - Type ’: ’ text / html ’ }) ;
31 res . end ( data ) ;
32 }) ;
33 }) ;
34
35 server . listen (8000 , () = > {
36 console . log ( ’ Serveur demarre sur http :// localhost :8000 ’) ;
37 }) ;
Listing 3 – Exercice 3 – [Link]
Fichiers HTML à créer :
3
Technologies Web Backend – Série 2 [Link] & [Link]
<! DOCTYPE html > < html lang = " fr " >< head > < meta charset = " UTF -8 " >
< title > Accueil </ title > </ head >
< body > < h1 > Bienvenue sur la page d ’ accueil ! </ h1 > </ body > </ html >
Listing 4 – [Link]
<! DOCTYPE html > < html lang = " fr " >< head > < meta charset = " UTF -8 " >
< title > A propos </ title > </ head >
< body > < h1 > A propos de nous </ h1 > </ body > </ html >
Listing 5 – [Link]
<! DOCTYPE html > < html lang = " fr " >< head > < meta charset = " UTF -8 " >
< title > Contact </ title > </ head >
< body > < h1 > Contactez - nous </ h1 > </ body > </ html >
Listing 6 – [Link]
4 1 Exercice
4 – Analyse d’URL avec le module url
Objectif
Analyser une URL complète et en extraire toutes les parties (protocole, hôte, chemin,
paramètres, fragment).
1 const url = require ( ’ url ’) ;
2
3 // URL a analyser
4 const myUrl = ’ https :// www . example . com / path / to / resource ’
5 + ’? name = Ahmed & age =22# section ’;
6
7 // Analyse de l ’ URL
8 const parsedUrl = new URL ( myUrl ) ;
9
10 console . log ( ’ Protocole : ’ , parsedUrl . protocol ) ; // https :
11 console . log ( ’ Hote : ’ , parsedUrl . host ) ; // www . example . com
12 console . log ( ’ Chemin : ’ , parsedUrl . pathname ) ; // / path / to /
resource
13 console . log ( ’ Recherche : ’ , parsedUrl . search ) ; // ? name = Ahmed & age
=22
14 console . log ( ’ Parametre name : ’ , parsedUrl . searchParams . get ( ’ name ’) ) ;
15 console . log ( ’ Parametre age : ’ , parsedUrl . searchParams . get ( ’ age ’) ) ;
16 console . log ( ’ Fragment : ’ , parsedUrl . hash ) ; // # section
17
18 // Creer une nouvelle URL avec chemin modifie
19 const newUrl = new URL ( ’ https :// www . example . com ’) ;
20 newUrl . pathname = ’/ nouveau / chemin ’;
21 newUrl . searchParams . set ( ’ ville ’ , ’ Fes ’) ;
22 newUrl . searchParams . set ( ’ pays ’ , ’ Maroc ’) ;
23 newUrl . hash = ’ info ’;
24
4
Technologies Web Backend – Série 2 [Link] & [Link]
25 console . log ( ’\ nNouvelle URL : ’ , newUrl . toString () ) ;
26 // = > https :// www . example . com / nouveau / chemin ? ville = Fes & pays = Maroc #
info
Listing 7 – Exercice 4 – [Link]
5 1 Exercice
5 – Serveur [Link] avec paramètres de requête
Objectif
Créer un serveur [Link] avec deux routes :
— GET / → retourne "home page"
— GET /contact?name=&age= → retourne une réponse personnalisée
npm init -y
npm install express
Listing 8 – Initialisation du projet
1 const express = require ( ’ express ’) ;
2 const app = express () ;
3
4 // Route GET /
5 app . get ( ’/ ’ , ( req , res ) = > {
6 res . send ( ’ home page ’) ;
7 }) ;
8
9 // Route GET / contact avec query params name et age
10 app . get ( ’/ contact ’ , ( req , res ) = > {
11 const { name , age } = req . query ;
12
13 if (! name || ! age ) {
14 return res . status (400) . send (
15 ’ Veuillez fournir les parametres name et age . ’
16 );
17 }
18
19 res . send (
20 ‘ Bonjour $ { name } , vous avez $ { age } ans . Bienvenue sur la page
contact ! ‘
21 );
22 }) ;
23
24 app . listen (8000 , () = > {
25 console . log ( ’ Serveur Express demarre sur http :// localhost :8000 ’) ;
26 }) ;
Listing 9 – Exercice 5 – [Link]
Tests :
nodemon app . js
5
Technologies Web Backend – Série 2 [Link] & [Link]
# Test page d ’ accueil
curl http :// localhost :8000/
# = > home page
# Test route contact
curl " http :// localhost :8000/ contact ? name = Jihad & age =25 "
# = > Bonjour Jihad , vous avez 25 ans . Bienvenue sur la page contact !
6 1 Exercice
6 – Query params vs Route params dans Express
Différence fondamentale
— Query params ([Link]) : après le ?, sous la forme clé=valeur, ex.
/hello?name=Jihad
— Route params ([Link]) : dans l’URL elle-même, ex. /user/:id → /user/123
1 const express = require ( ’ express ’) ;
2 const app = express () ;
3
4 // Route 1 : / hello ( query param )
5 app . get ( ’/ hello ’ , ( req , res ) = > {
6 const name = req . query . name || ’ inconnu ’;
7 res . send ( ‘ Hello , $ { name } ! ‘) ;
8 }) ;
9
10 // Route 2 : / user /: id ( route param )
11 app . get ( ’/ user /: id ’ , ( req , res ) = > {
12 const id = req . params . id ;
13 res . send ( ‘ User ID : $ { id } ‘) ;
14 }) ;
15
16 app . listen (8000 , () = > {
17 console . log ( ’ Serveur demarre sur http :// localhost :8000 ’) ;
18 }) ;
Listing 10 – Exercice 6 – [Link]
Tests :
curl " http :// localhost :8000/ hello ? name = Jihad "
# = > Hello , Jihad !
curl http :// localhost :8000/ user /123
# = > User ID : 123
6
Technologies Web Backend – Série 2 [Link] & [Link]
7 1 Exercice
7 – API REST avec [Link]
Objectif
Construire une API REST complète (CRUD) pour gérer une liste d’étudiants en mémoire,
avec validation et gestion d’erreurs.
1 const express = require ( ’ express ’) ;
2 const app = express () ;
3 app . use ( express . json () ) ;
4
5 // Donnees statiques
6 let students = [
7 { id : 1 , name : ’ Alami Ahmed ’ , note : 15 } ,
8 { id : 2 , name : ’ Benali Sara ’ , note : 17 } ,
9 { id : 3 , name : ’ Chakir Youssef ’ , note : 12 } ,
10 ];
11
12 // Middleware de validation de l ’ id
13 function validateId ( req , res , next ) {
14 const id = parseInt ( req . params . studentId , 10) ;
15 if ( isNaN ( id ) || id <= 0) {
16 return res . status (400) . json ({ error : ’ studentId doit etre un
nombre valide . ’ }) ;
17 }
18 req . studentId = id ;
19 next () ;
20 }
21
22 // GET / : liste complete
23 app . get ( ’/ ’ , ( req , res ) = > {
24 res . json ( students ) ;
25 }) ;
26
27 // GET /: studentId : un etudiant
28 app . get ( ’ /: studentId ’ , validateId , ( req , res ) = > {
29 const student = students . find ( s = > s . id === req . studentId ) ;
30 if (! student ) {
31 return res . status (404) . json ({ error : ’ Etudiant non trouve . ’ }) ;
32 }
33 res . json ( student ) ;
34 }) ;
35
36 // DELETE /: studentId : supprimer
7
Technologies Web Backend – Série 2 [Link] & [Link]
37 app . delete ( ’ /: studentId ’ , validateId , ( req , res ) = > {
38 const index = students . findIndex ( s = > s . id === req . studentId ) ;
39 if ( index === -1) {
40 return res . status (404) . json ({ error : ’ Etudiant non trouve . ’ }) ;
41 }
42 const deleted = students . splice ( index , 1) ;
43 res . json ({ message : ’ Etudiant supprime . ’ , student : deleted [0] }) ;
44 }) ;
45
46 // POST / ajouter : ajouter
47 app . post ( ’/ ajouter ’ , ( req , res ) = > {
48 const { id , name , note } = req . body ;
49 if (! id || ! name || note === undefined ) {
50 return res . status (400) . json ({ error : ’ Champs id , name et note
requis . ’ }) ;
51 }
52 const newStudent = { id , name , note };
53 students . push ( newStudent ) ;
54 res . status (201) . json ( newStudent ) ;
55 }) ;
56
57 // PUT /: studentId : mettre a jour
58 app . put ( ’ /: studentId ’ , validateId , ( req , res ) = > {
59 const index = students . findIndex ( s = > s . id === req . studentId ) ;
60 if ( index === -1) {
61 return res . status (404) . json ({ error : ’ Etudiant non trouve . ’ }) ;
62 }
63 students [ index ] = { ... students [ index ] , ... req . body , id : req .
studentId };
64 res . json ( students [ index ]) ;
65 }) ;
66
67 app . listen (8000 , () = > {
68 console . log ( ’ API demarree sur http :// localhost :8000 ’) ;
69 }) ;
Listing 11 – Exercice 7 – [Link]
8 1 Exercice
8 – API REST avec MySQL
Objectif
Créer une API REST (CRUD) connectée à une base de données MySQL
gestion_utilisateurs.
npm init -y
8
Technologies Web Backend – Série 2 [Link] & [Link]
npm install express mysql2
Listing 12 – Installation
CREATE DATABASE IF NOT EXISTS gestion_utilisateurs ;
USE gestion_utilisateurs ;
CREATE TABLE IF NOT EXISTS utilisateurs (
id INT AUTO_INCREMENT PRIMARY KEY ,
nom VARCHAR (255) NOT NULL ,
email VARCHAR (255) NOT NULL ,
age INT
);
Listing 13 – Script SQL – creation de la table
1 const express = require ( ’ express ’) ;
2 const mysql = require ( ’ mysql2 ’) ;
3 const app = express () ;
4 app . use ( express . json () ) ;
5
6 // Connexion MySQL
7 const db = mysql . createConnection ({
8 host : ’ localhost ’ ,
9 user : ’ root ’ ,
10 password : ’ ’ , // Remplacer par votre mot de passe
11 database : ’ gestion_utilisateurs ’
12 }) ;
13
14 db . connect ( err = > {
15 if ( err ) {
16 console . error ( ’ Erreur de connexion MySQL : ’ , err ) ;
17 process . exit (1) ;
18 }
19 console . log ( ’ Connecte a MySQL . ’) ;
20 }) ;
21
22 // GET / users
23 app . get ( ’/ users ’ , ( req , res ) = > {
24 db . query ( ’ SELECT * FROM utilisateurs ’ , ( err , results ) = > {
25 if ( err ) return res . status (500) . json ({ error : err . message }) ;
26 res . json ( results ) ;
27 }) ;
28 }) ;
29
30 // GET / users /: id
31 app . get ( ’/ users /: id ’ , ( req , res ) = > {
32 db . query ( ’ SELECT * FROM utilisateurs WHERE id = ? ’ ,
33 [ req . params . id ] ,
34 ( err , results ) = > {
9
Technologies Web Backend – Série 2 [Link] & [Link]
35 if ( err ) return res . status (500) . json ({ error : err . message }) ;
36 if ( results . length === 0)
37 return res . status (404) . json ({ error : ’ Utilisateur non trouve .
’ }) ;
38 res . json ( results [0]) ;
39 }
40 );
41 }) ;
42
43 // POST / users
44 app . post ( ’/ users ’ , ( req , res ) = > {
45 const { nom , email , age } = req . body ;
46 if (! nom || ! email )
47 return res . status (400) . json ({ error : ’ Les champs nom et email
sont requis . ’ }) ;
48
49 db . query ( ’ INSERT INTO utilisateurs ( nom , email , age ) VALUES (? , ? ,
?) ’ ,
50 [ nom , email , age ] ,
51 ( err , result ) = > {
52 if ( err ) return res . status (500) . json ({ error : err . message }) ;
53 res . status (201) . json ({ id : result . insertId , nom , email , age }) ;
54 }
55 );
56 }) ;
57
58 // PUT / users /: id
59 app . put ( ’/ users /: id ’ , ( req , res ) = > {
60 const { nom , email , age } = req . body ;
61 if (! nom || ! email )
62 return res . status (400) . json ({ error : ’ Les champs nom et email
sont requis . ’ }) ;
63
64 db . query ( ’ UPDATE utilisateurs SET nom =? , email =? , age =? WHERE id =? ’
,
65 [ nom , email , age , req . params . id ] ,
66 ( err , result ) = > {
67 if ( err ) return res . status (500) . json ({ error : err . message }) ;
68 if ( result . affectedRows === 0)
69 return res . status (404) . json ({ error : ’ Utilisateur non trouve .
’ }) ;
70 res . json ({ message : ’ Utilisateur mis a jour . ’ }) ;
71 }
72 );
73 }) ;
74
75 // DELETE / users /: id
10
Technologies Web Backend – Série 2 [Link] & [Link]
76 app . delete ( ’/ users /: id ’ , ( req , res ) = > {
77 db . query ( ’ DELETE FROM utilisateurs WHERE id = ? ’ ,
78 [ req . params . id ] ,
79 ( err , result ) = > {
80 if ( err ) return res . status (500) . json ({ error : err . message }) ;
81 if ( result . affectedRows === 0)
82 return res . status (404) . json ({ error : ’ Utilisateur non trouve .
’ }) ;
83 res . json ({ message : ’ Utilisateur supprime . ’ }) ;
84 }
85 );
86 }) ;
87
88 app . listen (8000 , () = > {
89 console . log ( ’ API MySQL demarree sur http :// localhost :8000 ’) ;
90 }) ;
Listing 14 – Exercice 8 – [Link]
9 1 Exercice
9 – API REST avec MongoDB Atlas et Mongoose
Objectif
Développer une application CRUD avec [Link], Express et MongoDB Atlas via Mongoose.
npm init -y
npm install express mongoose
Listing 15 – Installation
1 const express = require ( ’ express ’) ;
2 const mongoose = require ( ’ mongoose ’) ;
3 const app = express () ;
4 app . use ( express . json () ) ;
5
6 // Connexion MongoDB Atlas
7 const MONGO_URI =
8 ’ mongodb + srv :// < username >: < password > @cluster0 . mongodb . net / < dbname > ’
9 + ’? retryWrites = true & w = majority ’;
10
11 mongoose . connect ( MONGO_URI )
12 . then (() = > console . log ( ’ Connecte a MongoDB Atlas . ’) )
13 . catch ( err = > { console . error ( ’ Erreur MongoDB : ’ , err ) ; process .
exit (1) ; }) ;
14
15 // Schema et modele Utilisateur
16 const utilisateurSchema = new mongoose . Schema ({
11
Technologies Web Backend – Série 2 [Link] & [Link]
17 name : { type : String , required : true } ,
18 email : { type : String , required : true } ,
19 age : { type : Number } ,
20 }) ;
21
22 const Utilisateur = mongoose . model ( ’ Utilisateur ’ , utilisateurSchema ) ;
23
24 // POST / users -- Creer
25 app . post ( ’/ users ’ , async ( req , res ) = > {
26 try {
27 const { name , email , age } = req . body ;
28 if (! name || ! email )
29 return res . status (400) . json ({ error : ’ name et email sont requis
. ’ }) ;
30
31 const newUser = new Utilisateur ({ name , email , age }) ;
32 await newUser . save () ;
33 res . status (201) . json ( newUser ) ;
34 } catch ( err ) {
35 res . status (500) . json ({ error : err . message }) ;
36 }
37 }) ;
38
39 // GET / users -- Lire tous
40 app . get ( ’/ users ’ , async ( req , res ) = > {
41 try {
42 const users = await Utilisateur . find () ;
43 res . json ( users ) ;
44 } catch ( err ) {
45 res . status (500) . json ({ error : err . message }) ;
46 }
47 }) ;
48
49 // GET / users /: id -- Lire un
50 app . get ( ’/ users /: id ’ , async ( req , res ) = > {
51 try {
52 const user = await Utilisateur . findById ( req . params . id ) ;
53 if (! user )
54 return res . status (404) . json ({ error : ’ Utilisateur non trouve . ’
}) ;
55 res . json ( user ) ;
56 } catch ( err ) {
57 res . status (500) . json ({ error : err . message }) ;
58 }
59 }) ;
60
61 // PUT / users /: id -- Mettre a jour
12
Technologies Web Backend – Série 2 [Link] & [Link]
62 app . put ( ’/ users /: id ’ , async ( req , res ) = > {
63 try {
64 const { name , email , age } = req . body ;
65 if (! name || ! email )
66 return res . status (400) . json ({ error : ’ name et email sont requis
. ’ }) ;
67
68 const updated = await Utilisateur . findByIdAndUpdate (
69 req . params . id ,
70 { name , email , age } ,
71 { new : true , runValidators : true }
72 );
73 if (! updated )
74 return res . status (404) . json ({ error : ’ Utilisateur non trouve . ’
}) ;
75 res . json ( updated ) ;
76 } catch ( err ) {
77 res . status (500) . json ({ error : err . message }) ;
78 }
79 }) ;
80
81 // DELETE / users /: id -- Supprimer
82 app . delete ( ’/ users /: id ’ , async ( req , res ) = > {
83 try {
84 const deleted = await Utilisateur . findByIdAndDelete ( req . params . id
);
85 if (! deleted )
86 return res . status (404) . json ({ error : ’ Utilisateur non trouve . ’
}) ;
87 res . json ({ message : ’ Utilisateur supprime . ’ , user : deleted }) ;
88 } catch ( err ) {
89 res . status (500) . json ({ error : err . message }) ;
90 }
91 }) ;
92
93 app . listen (8000 , () = > {
94 console . log ( ’ API MongoDB demarree sur http :// localhost :8000 ’) ;
95 }) ;
Listing 16 – Exercice 9 – [Link]
Résumé des routes de l’API (Exercices 7–9)
Méthode Route Description
GET /users Récupérer tous les utilisateurs
GET /users/:id Récupérer un utilisateur par ID
POST /users Créer un nouvel utilisateur
PUT /users/:id Mettre à jour un utilisateur
DELETE /users/:id Supprimer un utilisateur
13