-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·86 lines (74 loc) · 2.2 KB
/
server.js
File metadata and controls
executable file
·86 lines (74 loc) · 2.2 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
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
var path = require("path");
var fs = require('fs');
var mysql = require("mysql");
var bodyParser = require('body-parser');
var express = require('express'),app = express(),port = process.env.PORT || 3000;
//Easy JSON parsing
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//DATABASE
const con = mysql.createConnection({
host: "localhost",
user: "raspberry",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected to database!");
});
con.query('USE NodeJS', function (err) {
if (err) throw err;
});
//Allows us to add files in our /public folder
app.use(express.static(path.join(__dirname,"public")));
//Functions
function writeToLog(txt){ //Create a local logfile
var fs = require('fs');
fs.appendFile('log.txt', txt, function (err) {
if (err) throw err;
});
}
//ROUTING
app.get("/", function(req,res){
res.send("Hello world");//This is never called because of index.html in /public
});
app.post("/add", function(req,res){
con.query('INSERT INTO test SET ?', req.body,
function (err, result) {
if (err) throw err;
res.send(result);
writeToLog(Date()+" INSERT: "+JSON.stringify(req.body)+JSON.stringify(result)+"\n");
}
);
});
app.post("/remove", function(req,res){
con.query('DELETE FROM test WHERE ?', req.body,
function (err, result) {
if (err) throw err;
res.send(result);
writeToLog(Date()+" DELETE: "+JSON.stringify(req.body)+JSON.stringify(result)+"\n");
}
);
});
app.post("/modify", function(req,res){
con.query('UPDATE test SET status='+req.body.status+' WHERE id='+req.body.id,
function (err, result) {
if (err) throw err;
res.send(result);
writeToLog(Date()+" MODIFY: "+JSON.stringify(req.body)+JSON.stringify(result)+"\n");
}
);
});
app.get("/list", function(req,res){
con.query('SELECT * FROM test',
function (err, result) {
if (err) throw err;
res.send(result);
}
);
});
//Start listening
app.listen(port);
console.log('todo list API server started on: ' + port);