-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
107 lines (86 loc) · 2.65 KB
/
app.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var http = require('http');
var url = require('url');
var router = require('routes')();
var swig = require('swig');
var qString = require('querystring');
var connection = require('mysql');
var con = connection.createConnection({
host : "localhost",
port : 3306,
database: "nodejs",
user : "root",
password: ""
});
router.addRoute('/',function(req,res){
con.query("SELECT * FROM mahasiswa",(err,rows,field) => {
if(err) throw err;
var html = swig.compileFile('./template/index.html')({
title : "Data mahasiswa",
data : rows
});
res.writeHead(200,{"Content-Type" : "text/html"});
res.end(html);
});
});
router.addRoute('/insert',(req,res) => {
if(req.method.toUpperCase() == "POST"){
var data_post = "";
req.on('data',(chuncks)=>{
data_post += chuncks;
});
req.on('end',function(){
data_post = qString.parse(data_post);
con.query("insert into mahasiswa set ?",data_post,(err,field) => {
if(err) throw err;
res.writeHead(302,{"Location" : "/"});
res.end();
});
});
}else{
var html = swig.compileFile('./template/form.html')();
res.writeHead(200,{"Content-Type" : "text/html"});
res.end(html);
}
});
router.addRoute('/update/:id',(req,res) => {
console.log(this.params.id);
con.query("select * from mahasiswa where ?",
{
no_induk : this.params.id
},(err,rows,field) =>{
if(rows.length){
var data = rows[0];
if(req.method.toUpperCase() == "POST")
{
}else{
var html = swig.compileFile("./template/form_update.html")({
data : data
});
res.writeHead(200,{"Content-Type" : "text/html"});
res.end(html);
}
}
});
});
router.addRoute('/delete',(req,res) => {
con.query("DELETE FROM mahasiswa WHERE ?",{
no_induk : "123456781"
},(err,fields) => {
if(err)throw err;
res.writeHead(200,{"Content-Type" : "text/plain"});
res.end(fields.affectedRows+" Rows Deleted");
});
});
http.createServer((req,res) => {
var path = url.parse(req.url).pathname;
var match = router.match(path);
if(match)
{
match.fn(req,res);
}else{
var html = swig.compileFile('./template/404.html')();
res.writeHead(404,{"Content-Type" : "text/html"});
res.end(html);
}
}).listen(8888);
console.log("Server is running.....");