-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
53 lines (49 loc) · 1.44 KB
/
router.js
File metadata and controls
53 lines (49 loc) · 1.44 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
var pg = require('pg');
var constring = 'tcp://node@localhost/ledenadmin';
var handleError = function (err, req, res) {
if (err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end();
}
};
var route = function (req, res) {
var data;
console.log(req.method + ": " + req.url);
if (req.url == '/leden') {
if (req.method == "GET") {
data = {};
pg.connect(constring, function (err, client) {
if (err) {
handleError(err, res, req);
return;
}
client.query('select * from members', function (err, result) {
data = result.rows;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(data));
});
});
} else if (req.method == "POST") {
data = "";
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
pg.connect(constring, function(err, client) {
if (err) {
handleError(err, res, req);
return;
}
var newMember = JSON.parse(data);
client.query("insert into members (name) values ('" + newMember.name + "')");
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({status: 'ok'}));
});
});
}
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('File not found.');
}
};
module.exports.route = route;