-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
104 lines (91 loc) · 1.95 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
const Hapi = require('hapi');
const vision = require('vision');
const User = require('./models/user.js');
// create a server with a host and port
var server = new Hapi.Server();
// add server’s connection information
server.connection({
host: 'localhost',
port: 3000
})
//Set route
server.route({
method:'GET',
path:'/',
handler:(request,reply)=>{
reply('Hello World');
}
});
//Dyanmic Routing
server.route({
method:'GET',
path:'/user/{name}',
handler:(request,reply)=>{
reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
}
});
//Static page
server.register(require('inert'),(err)=>{
if(err) throw err;
server.route({
method:'GET',
path:'/about',
handler:(request,reply)=>{
reply.file('./public/about.html');
}
});
});
//Templates
server.register(vision,(err)=>{
if(err) throw err;
server.views({
engines:{
html:require('ejs')
},
path:__dirname +'/views'
});
});
//Form page
server.route({
method:'GET',
path:'/add',
handler:(request,reply)=>{
reply.view('add');
}
});
//Add data into mongodb
server.route({
method:'POST',
path:'/add/user',
handler:(request,reply)=>{
let name = request.payload.name;
let email = request.payload.email;
var newUser = new User({
name:name,
email:email
});
newUser.save((err)=>{
if (err) throw err;
console.log('saved');
reply.redirect();
});
}
});
//GET the user
server.route({
method:'GET',
path:'/list',
handler:(request,reply)=>{
User.find({}).exec((err,data)=>{
if (err) throw err;
reply.view('index',{data:data})
});
}
});
// start your server
server.start(function(err) {
if (err) {
throw err;
}
console.log('Server running at: ',server.info.uri);
});