-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouting-server.js
45 lines (37 loc) · 1.35 KB
/
routing-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
const http = require('http');
const requestListener = (request, response) => {
response.setHeader('Content-Type', 'text/html');
response.statusCode = 200;
const { method, url } = request;
if(url === '/') {
if(method === 'GET') {
response.end('<h1>Ini adalah homepage</h1>');
} else {
response.end(`<h1>Halaman tidak dapat diakses dengan ${method} request</h1>`);
}
} else if(url === '/about') {
if(method === 'GET') {
response.end('<h1>Halo! Ini adalah halaman about</h1>')
} else if(method === 'POST') {
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
});
request.on('end', () => {
body = Buffer.concat(body).toString();
const { name } = JSON.parse(body);
response.end(`<h1>Halo, ${name}! Ini adalah halaman about</h1>`);
});
} else {
response.end(`<h1>Halaman tidak dapat diakses menggunakan ${method} request</h1>`);
}
} else {
response.end('<h1>Halaman tidak ditemukan!</h1>');
}
};
const server = http.createServer(requestListener);
const port = 5000;
const host = 'localhost';
server.listen(port, host, () => {
console.log(`Server berjalan pada http://${host}:${port}`);
});