-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
67 lines (56 loc) · 1.33 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const http = require('http');
const todos = [
{
id: 1,
text: 'Todo One',
},
{
id: 2,
text: 'Todo Two',
},
{
id: 3,
text: 'Todo Three',
},
];
const server = http.createServer((req, res) => {
const { method, url } = req;
// console.log(req.headers.authorization);
let body = [];
req
.on('data', (chunk) => {
body.push(chunk);
})
.on('end', () => {
body = Buffer.concat(body).toString();
let status = 404;
const response = {
success: false,
data: null,
error: null,
};
if (method === 'GET' && url === '/todos') {
status = 200;
response.success = true;
response.data = todos;
} else if (method === 'POST' && url === '/todos') {
const { id, text } = JSON.parse(body);
if (!id || !text) {
status = 400;
response.error = 'please,add id and text!';
} else {
todos.push({ id, text });
status = 201;
response.success = true;
response.data = todos;
}
}
res.writeHead(status, {
'Content-Type': 'Application/json',
'X-Powered-By': 'Node.js',
});
res.end(JSON.stringify(response));
});
});
const PORT = 5000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));