-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
57 lines (46 loc) · 1.36 KB
/
main.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
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;
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.writeHeader(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}`));