-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03_server.js
54 lines (42 loc) · 1.42 KB
/
03_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
// const http = require("http");
// const port = process.env.PORT || 1337;
// 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");
// }
// const server = http.createServer((req, res) => {
// if (req.url === "/") return respondText(req, res);
// if (req.url === "/json") return respondJson(req, res);
// respondNotFound(req, res);
// });
// server.listen(port);
// console.log(`Listening on port ${port}`);
const http = require("http");
const port = process.env.PORT || 1337;
const server = http.createServer((req, res) => {
if (req.url === "/") return respondText(req, res);
if (req.url === "/json") return respondJson(req, res);
respondNotFound(req, res);
});
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({ name: "John" }));
}
function respondNotFound(req, res) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}
server.listen(port);
console.log(`Server listening on port ${port}`);