-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_server.js
92 lines (76 loc) · 2.48 KB
/
04_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// const http = require("http");
// const port = process.env.PORT || 1337;
// const querystring = require("querystring");
// function respondText(req, res) {
// res.setHeader("Content-Type", "text/plain");
// res.end("Hello");
// }
// function respondJson(req, res) {
// res.setHeader("Content-Type", "application/json");
// res.end(JSON.stringify({ text: "Hi", number: [1, 2, 3] }));
// }
// function respondNotFound(req, res) {
// res.writeHead(404, { "Content-Type": "text/plain" });
// res.end("Not Found");
// }
// // Dynamic Responses
// function respondEcho(req, res) {
// const { input = "" } = querystring.parse(
// req.url.split("?").splice(1).join("")
// );
// res.setHeader("Content-Type", "application/json");
// res.end(
// JSON.stringify({
// // normal, shouty, characterCount, backwards
// normal: input,
// shouty: input.toUpperCase(),
// characterCount: input.length,
// backwards: input.split("").reverse().join(""),
// })
// );
// }
// const server = http.createServer((req, res) => {
// if (req.url === "/") return respondText(req, res);
// if (req.url === "/json") return respondJson(req, res);
// if (req.url.match(/^\/echo/)) return respondEcho(req, res);
// respondNotFound(req, res);
// });
// server.listen(port);
// console.log(`Listening to port ${port}`);
const http = require("http");
const querystring = require("querystring");
const port = process.env.PORT || 1337;
function respondText(req, res) {
res.setHeader("Content-Type", "text/plain");
res.end("Hello User");
}
function respondJson(req, res) {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ name: "John" }));
}
function respondNotFound(req, res) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}
function respondEcho(req, res) {
const { input = "" } = querystring.parse(
req.url.split("?").splice(1).join("")
);
res.setHeader("Content-Type", "application/json");
res.end(
JSON.stringify({
normal: input,
shouty: input.toUpperCase(),
characterCount: input.length,
backwards: input.split("").reverse().join(""),
})
);
}
const server = http.createServer((req, res) => {
if (req.url === "/") return respondText(req, res);
if (req.url === "/json") return respondJson(req, res);
if (req.url.match(/^\/echo/)) return respondEcho(req, res);
respondNotFound(req, res);
});
server.listen(port);
console.log(`Server running on port ${port}`);