-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
58 lines (50 loc) · 1.57 KB
/
main.js
File metadata and controls
58 lines (50 loc) · 1.57 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
const http = require('http');
const url = require('url');
var messages = [];
var helloWorld = {
"message": "Hello world!"
};
var fourZeroFour = {
"message": "404, not found!"
};
// no use as of now
function handler(request, response) {
var uri = url.parse(request.url);
console.log(uri.pathname, 'was requested');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World!');
}
function postBody(request, callback) {
var body = '';
request.on('data', function(chunk) {
body += chunk;
})
request.on('end', function() {
callback(body);
})
}
function api(request, response) {
var method = request.method;
var uri = url.parse(request.url);
console.log(method, uri.pathname, 'was requested');
if(method == 'POST' && uri.pathname == '/api/message') {
postBody(request, function(body) {
var message = JSON.parse(body);
messages.push(message);
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify({"success": true}, null, 5));
});
}
else if(method == 'GET' && uri.pathname == '/api/messages') {
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(messages, null, 5));
}
else {
response.writeHead(404, {'Content-Type': 'application/json'});
response.end(JSON.stringify(fourZeroFour, null, 5));
}
}
var server = http.createServer(api);
var port = 8080;
server.listen(port);
console.log('Server started at port', port);