-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
98 lines (81 loc) · 2.67 KB
/
server.js
File metadata and controls
98 lines (81 loc) · 2.67 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import http from 'http';
import { MongoClient } from 'mongodb';
const client = new MongoClient("mongodb://localhost:27017");
const db = client.db("student").collection("students");
//
// console.log("Inserted Successfully")
// const obj = {
// id:id1,
// name: name1,
// dept: dept1
// }
async function fetchData() {
try {
const data = await db.find({}).toArray();
// console.log(data)
return data;
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
}
http.createServer(async (req, res)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
console.log(req.url)
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
if (req.method === 'POST' && req.url === '/insert') {
let body = '';
req.on('data', chunk => {
// console.log(chunk.toString())
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
data.id = parseInt(data.id)
// console.log('Received data:', data);
db.insertOne(data);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Data received successfully' }));
});
}
else if(req.method === 'GET' && req.url === '/display'){
const prom = await fetchData();
// console.log(prom)
const data = JSON.stringify(prom);
res.end(data)
// prom.then(data => {
// // console.log('Data:', data);
// return data;
// })
// .catch(error => {
// // console.error('Error:', error);
// return error;
// });
}
else if(req.method === 'POST' && req.url === '/remove'){
let body = '';
req.on('data', chunk => {
// console.log(chunk.toString())
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
// console.log('Received data:', data);
db.deleteOne({id:parseInt(data.id)})
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Data recieved successfully' }));
});
}
else {
res.writeHead(404);
res.end();
}
}).listen(3000, ()=>{
console.log(`The server is running at ${3000}`)
})