Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (77 loc) · 1.42 KB
/
Copy pathindex.js
File metadata and controls
84 lines (77 loc) · 1.42 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
var http=require("http");
var qs=require("querystring");
var items=[];
http.createServer(function(req,res){
if(req.url=="/"){
switch(req.method)
{
case "GET":
show(res);
break;
case "POST":
add(req,res);
break;
default:
badRequest(res);
}
}
else{
notFound(res);
}
}).listen(3000,function(){
console.log("server is running....");
})
function show(res){
var itemsStr=items.map(function(item){
return "<li>"+item+"</li>";
}).join("");
var html=`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>To-Do List</h1>
<ul>
${itemsStr}
</ul>
<form method="post" action="/">
<p><input type="text" name="item"></p>
<p><input type="text" name="name"></p>
<p><input type="submit" value="add item"></p>
</form>
</body>
</html>
`;
res.writeHead(200,{
"Content-Type":"text/html;charset=utf-8",
"Content-Lenght":Buffer.byteLength(html)
});
res.end(html);
}
function add(req,res){
var data="";
req.setEncoding("utf8");
req.on("data",function(chunk){
data+=chunk;
})
req.on("end",function(){
console.log(data);
let item=qs.parse(data).item;
items.push(item);
show(res);
})
}
function notFound(res){
res.writeHead(404,{
"Content-Type":"text/plain"
});
res.end("Not Found!");
}
function badRequest(res){
res.writeHead(500,{
"Content-Type":"text/plain"
});
res.end("Bad Request!");
}