-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
81 lines (71 loc) · 2.02 KB
/
app.js
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
const { json } = require('body-parser');
const exp = require('constants');
const express = require('express');
const fs = require('fs');
let etudiants = [];
fs.readFile("./bd/etudiants.json", (err, data) => {
if(err){
return
}else{
etudiants.push(...JSON.parse(data));
}
});
const Port = 3000;
const app = express();
app.use(express.static('.'))
app.use(express.json());
app.get('/etudiants',(req,res)=>{
res.json(etudiants);
});
app.post('/etudiants',(req,res)=>{
let {nom,prenom,age} = req.body;
if(nom=="" || prenom==""||age=="")
{
return res.status(400).json({error:"les Donne sont vides"});
}
fs.readFile("./bd/index.txt", (err,data)=>{
let id = parseInt(data);
let etudiant ={
id,
nom,
prenom,
age
}
console.log(etudiant.id);
etudiants.push(etudiant);
fs.writeFile("./bd/etudiants.json", JSON.stringify(etudiants,null,3), (err)=>{
if(err)
{
res.status(500).json({
error:"we are sorry"
});
}else{
res.status(201).json(etudiants);
id++;
fs.writeFile("./bd/index.txt",id+"",(err)=>{
});
}
});
})
});
app.delete('/etudiants/:id',(req,res)=>{
let etudiant = etudiants.find((ele)=>{return (ele.id==req.params.id)});
if(!etudiant)
{
return res.status(404).json({error:"erreur mesage"});
}
etudiants = etudiants.filter(ele=>ele.id!=req.params.id);
console.log(etudiants);
fs.writeFile('./bd/etudiants.json',JSON.stringify(etudiants),(err)=>{
if(err)
{
return res.status(500).json({err:"erreur messgain deletinng"});
}else{
return res.status(200).json(etudiant);
}
})
})
// c e
app.listen(Port,()=>{
console.log("Server is running");
})