-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
46 lines (36 loc) · 1.09 KB
/
server.js
File metadata and controls
46 lines (36 loc) · 1.09 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
const http = require("http");
const url = require("url");
const {
getStudents,
getStudentById,
createStudent,
updateStudent,
deleteStudent
} = require("./controllers/studentController");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
const method = req.method;
res.setHeader("Content-Type", "application/json");
if (path === "/students" && method === "GET") {
return getStudents(req, res, parsedUrl.query);
}
if (path === "/students" && method === "POST") {
return createStudent(req, res);
}
const studentIdMatch = path.match(/^\/students\/(.+)$/);
if (studentIdMatch) {
const id = studentIdMatch[1];
if (method === "GET") return getStudentById(req, res, id);
if (method === "PUT") return updateStudent(req, res, id);
if (method === "DELETE") return deleteStudent(req, res, id);
}
res.writeHead(404);
res.end(JSON.stringify({
success: false,
message: "Route not found"
}));
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});