-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
120 lines (115 loc) · 2.97 KB
/
Copy pathserver.js
File metadata and controls
120 lines (115 loc) · 2.97 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const http = require("http");
const { v4: uuidv4 } = require("uuid");
const errHandle = require("./errorHandle");
const todos = [];
const requestListener = (req, res) => {
const headers = {
"Access-Control-Allow-Headers":
"Content-Type, Authorization, Content-Length, X-Requested-With",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "PATCH, POST, GET,OPTIONS,DELETE",
"Content-Type": "application/json",
};
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
if (req.url == "/todos" && req.method == "GET") {
res.writeHead(200, headers);
res.write(
JSON.stringify({
status: "success",
data: todos,
})
);
res.end();
} else if (req.url == "/todos" && req.method == "POST") {
req.on("end", () => {
try {
const title = JSON.parse(body).title;
if (title !== undefined) {
const todo = {
title: title,
id: uuidv4(),
};
todos.push(todo);
res.writeHead(200, headers);
res.write(
JSON.stringify({
status: "success",
data: todos,
})
);
res.end();
} else {
errHandle(res);
}
} catch (error) {
errHandle(res);
}
});
} else if (req.url == "/todos" && req.method == "DELETE") {
todos.length = 0;
res.writeHead(200, headers);
res.write(
JSON.stringify({
status: "success",
data: todos,
})
);
res.end();
} else if (req.url.startsWith("/todos/") && req.method == "DELETE") {
const id = req.url.split("/").pop();
const index = todos.findIndex(element => element.id == id);
if(index !== -1){
todos.splice(index, 1);
res.writeHead(200, headers);
res.write(
JSON.stringify({
status: "success",
data: todos,
})
);
res.end();
}else{
errHandle(res);
}
} else if (req.url.startsWith("/todos/") && req.method == "PATCH") {
req.on("end", () => {
try {
const todo = JSON.parse(body).title;
const id = req.url.split("/").pop();
const index = todos.findIndex(element => element.id == id);
if(todo !== undefined && index !== -1){
todos[index].title = todo;
res.writeHead(200, headers);
res.write(
JSON.stringify({
status: "success",
data: todos,
})
);
res.end();
}else{
errHandle(res);
}
} catch (error) {
errHandle(res);
}
});
} else if (req.method == "OPTIONS") {
res.writeHead(200, headers);
res.end();
} else {
res.writeHead(404, headers);
res.write(
JSON.stringify({
status: "false",
message: "無此網站路由",
})
);
res.end();
}
};
const server = http.createServer(requestListener);
server.listen(process.env.PORT || 3005);