-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (67 loc) · 2.23 KB
/
server.js
File metadata and controls
75 lines (67 loc) · 2.23 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
var http = require('http'),
express = require('express'),
app = express(),
sqlite3 = require('sqlite3').verbose(),
bodyParser = require('body-parser'),
db = new sqlite3.Database('emails-database');
/* We add configure directive to tell express to use Jade to
render templates */
app.set('views', __dirname + '/public');
app.engine('.html', require('jade').__express);
app.use(express.static(__dirname + '/public'));
// Allows express to get data from POST requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Database initialization
db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='emails'", function(err, row) {
if(err !== null) {
console.log(err);
}
else if(row == null) {
db.run('CREATE TABLE "emails" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "email" VARCHAR(255), number VARCHAR(255))', function(err) {
if(err !== null) {
console.log(err);
}
else {
console.log("SQL Table 'emails' initialized.");
}
});
}
else {
console.log("SQL Table 'emails' already initialized.");
}
});
// We render the templates with the data
app.get('/', function(req, res) {
var params = {
"placeholder": "placeholder"
};
res.render('index.jade', params, function(err, html) {
res.send(html);
});
});
// We define a new route that will handle bookmark creation
app.post('/add', function(req, res) {
email = req.body.email;
number = req.body.number;
sqlRequest = "INSERT INTO 'emails' (email, number) VALUES('" + email + "', '" + number + "')"
db.run(sqlRequest, function(err) {
if(err !== null) {
res.status(500).send("An error has occurred -- " + err);
}
else {
res.redirect('/');
}
});
});
/* This will allow Cozy to run your app smoothly but
it won't break other execution environment */
var port = process.env.PORT || 9250;
var host = process.env.HOST || "127.0.0.1";
// Starts the server itself
var server = http.createServer(app).listen(port, host, function() {
console.log("Server listening to %s:%d within %s environment",
host, port, app.get('env'));
});