-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
70 lines (54 loc) · 1.36 KB
/
server.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
var express=require('express');
var app= express();
var bodyparser=require('body-parser');
var products=[
{
id:1,
name:'Bed'
},
{
id:2,
name:'Microwave'
}
];
var currentId=2;
var PORT=process.env.PORT || 3000;
app.use(express.static(__dirname)); //root folder
app.use(bodyparser.json());// allows to read data inside the request
app.get('/products',function(req,res){//route to the data
res.send({products:products});
});
app.post('/products',function(req,res){
var productName=req.body.name;
currentId++;
products.push({
id:currentId,
name:productName,
});
res.send('Successfully created the product');
});
app.put('/products/:id',function(req,res){
var id=req.params.id;//parameters
var newName=req.body.newName;
var found= false;
products.forEach(function(product,index){
if(!found && product.id===Number(id) ){
product.name=newName;
}
});
res.send('Successfully updated the product');
});
app.delete('/products/:id',function(req,res){
var id=req.params.id;
var found= false;
products.forEach(function(product,index){
console.log(index);
if(!found && product.id===Number(id)){
products.splice(index,1);
}
});
res.send("successfully deleted the product");
});
app.listen(PORT,function(){
console.log("server listening on "+ PORT);
});