-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
84 lines (60 loc) · 2.13 KB
/
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
73
74
75
76
77
78
79
80
81
82
83
84
const express = require('express');
const articleRouter = require('./routes/articles');
const methodOverride = require('method-override');
const initializePassport = require('./passport-config')
const bcrypt = require('bcrypt')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const app = express();
//********** DATABASE CODE ***********/
const mongoose = require('mongoose');
const Article = require('./models/article');
const db = mongoose.connection;
const url = "mongodb+srv://frontEnd:[email protected]/test?retryWrites=true&w=majority";
db.on('error', console.error); // log any errors that occur
// bind a function to perform when the database has been opened
db.once('open', function() {
// perform any queries here, more on this later
console.log("Connected to DB!");
});
process.on('SIGINT', function() {
// process is a global object referring to the system process running this
// code, when you press CTRL-C to stop Node, this closes the connection
mongoose.connection.close(function () {
console.log('DB connection closed by Node process ending');
process.exit(0);
});
});
(async () => {
try {
mongoose.set('useCreateIndex', true);
await mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true, });
} catch (error) {
console.error(error);
}
})();
//********** DATABASE CODE ENDS ***********/
app.use(flash())
app.use(session({
secret: '1234', // process.env.SESSION_SECRET
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.set('view engine', 'ejs');
// Public folder
app.use(express.static('./public'));
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));
app.get('/', async (req, res) => {
const articles = await Article.find().sort({
createdAt: 'desc'
});
res.render('articles/', { articles });
});
const PORT = 80;
app.use('/articles', articleRouter);
app.listen(process.env.PORT || PORT);
console.log(`Server running on localhost`);