-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.js
72 lines (53 loc) · 1.5 KB
/
http_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
68
69
70
71
72
/**
* Created by ebeljea on 10/24/16.
*/
var http = require('http');
var mysql = require('mysql');
const PORT = 8080;
var req = {
"professeur": "select * from professeur where id = ?",
"etudiant": "select * from etudiant where id = ?"
};
function handleRequest(request, response) {
console.log(request.url);
var url = request.url;
var tid = url.split("/")[1];
var profid = url.split("/")[2];
var connection = mysql.createConnection({
host: 'localhost',
user: 'ebeljea',
password: '',
database: 'MonApplication'
});
connection.connect(function (err) {
if (err) throw err;
handleConnection(response, connection, tid, profid);
});
}
function handleConnection(response, connection, tid, profid) {
connection.query(
{
sql: req[tid],
values: [profid]
},
function (err, rows) {
try {
encodeAndSend(err, rows, response, connection)
} catch (err) {
console.log(err);
response.statusCode = 500;
response.statusMessage = "Server Error!";
response.end();
}
}
)
}
function encodeAndSend(err, rows, response, connection) {
if (err) throw err;
response.end(JSON.stringify(rows));
connection.end();
}
var server = http.createServer(handleRequest);
server.listen(PORT, function () {
console.log("Server listening on: http://localhost:%s", PORT);
});