-
Notifications
You must be signed in to change notification settings - Fork 45
/
server.js
46 lines (38 loc) · 1.09 KB
/
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
'use strict';
const http = require('node:http');
const PORT = 8000;
const user = { name: 'jura', age: 22 };
const routing = {
'/': '<h1>welcome to homepage</h1><hr>',
'/user': user,
'/user/name': () => user.name.toUpperCase(),
'/user/age': () => user.age,
'/hello': { hello: 'world', andArray: [1, 2, 3, 4, 5, 6, 7] },
'/api/method1': (req, res) => {
console.log(req.url + ' ' + res.statusCode);
return { status: res.statusCode };
},
'/api/method2': (req) => ({
user,
url: req.url,
cookie: req.headers.cookie
}),
};
const types = {
object: (o) => JSON.stringify(o),
string: (s) => s,
undefined: () => 'not found',
function: (fn, req, res) => JSON.stringify(fn(req, res)),
};
http.createServer((req, res) => {
const data = routing[req.url];
const type = typeof data;
const serializer = types[type];
const result = serializer(data, req, res);
res.end(result);
}).listen(PORT);
// http.createServer((req, res) => {
// const data = routing[req.url];
// res.end(types[typeof data](data, req, res));
// }).listen(PORT);
setInterval(() => user.age++, 2000);