-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (63 loc) · 2.45 KB
/
server.js
File metadata and controls
71 lines (63 loc) · 2.45 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
const http = require('http');
const requestListener = (request, response) => {
// response.setHeader('Content-Type', 'text/html');
// response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
response.setHeader('X-Powered-By', 'NodeJS');
const { method, url } = request;
if(url === '/') {
if(method === 'GET') {
response.statusCode = 200;
// response.end('<h1>Ini adalah homepage</h1>');
response.end(JSON.stringify({
message: 'Ini adalah homepage',
}));
} else {
response.statusCode = 400;
// response.end(`<h1>Halaman tidak dapat diakses dengan ${method} request</h1>`);
response.end(JSON.stringify({
message: `Halaman tidak dapat diakses dengan ${method} request`,
}));
}
} else if(url === '/about') {
if(method === 'GET') {
response.statusCode = 200;
// response.end('<h1>Halo! Ini adalah halaman about</h1>')
response.end(JSON.stringify({
message: 'Halo! Ini adalah halaman about',
}));
} 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.statusCode = 200;
// response.end(`<h1>Halo, ${name}! Ini adalah halaman about</h1>`);
response.end(JSON.stringify({
message: `Halo, ${name}! Ini adalah halaman about`,
}));
});
} else {
response.statusCode = 400;
// response.end(`<h1>Halaman tidak dapat diakses menggunakan ${method} request</h1>`);
response.end(JSON.stringify({
message: `Halaman tidak dapat diakses menggunakan ${method}, request`
}));
}
} else {
response.statusCode = 404;
// response.end('<h1>Halaman tidak ditemukan!</h1>');
response.end(JSON.stringify({
message: 'Halaman tidak ditemukan!',
}));
}
};
const server = http.createServer(requestListener);
const port = 5000;
const host = 'localhost';
server.listen(port, host, () => {
console.log(`Server berjalan pada http://${host}:${port}`);
});