-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (48 loc) · 1.08 KB
/
index.js
File metadata and controls
61 lines (48 loc) · 1.08 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
const http = require('http')
const { parse } = require('url')
const getUsers = (req, res) => {
res.writeHead(200, {
'Content-Type': 'applitcation/json',
})
res.write(JSON.stringify([{ id: 1 }]))
res.end()
}
const createUser = (req, res) => {
const body = []
req.on('data', (chunck) => {
body.push(chunck)
})
req.on('end', () => {
const parsedBody = Buffer.concat(body)
.toString()
.split('&')
.map((item) => item.split('='))
.reduce(
(memo, current) => ({
...memo,
[current[0]]: current[1],
}),
{}
)
// db.save(parsedBody)
res.writeHead(200, {
'Content-Type': 'applitcation/json',
})
res.write(JSON.stringify(parsedBody))
res.end()
})
}
const routes = {
'/users': {
GET: getUsers,
POST: createUser,
},
}
const server = http.createServer((req, res) => {
const url = parse(req.url)
if (routes[url.pathname] && routes[url.pathname][req.method]) {
routes[url.pathname][req.method](req, res)
}
})
server.listen(3000)
// GET http://localhost:3000