-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.js
96 lines (80 loc) · 2.61 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
85
86
87
88
89
90
91
92
93
94
95
96
// ******************************************
// INITIALIZATION
// ******************************************
// Server specific version of Zone.js for SSR
require('zone.js/dist/zone-node');
// Dependencies
const express = require('express');
const ngUniversal = require('@nguniversal/express-engine');
const path = require('path');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
// Express and Port
const app = express();
const port = process.env.PORT || 3000;
// Server Bundle
const appServer = require('./dist-server/main.bundle');
// Connect to database via mongoose
mongoose.connect(config.database)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// Routes
const angular = require('./routes/angular');
const users = require('./routes/users');
// ******************************************
// MIDDLEWARE
// ******************************************
// Cross-Origin Resource Sharing (CORS)
app.use(cors());
// Body Parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Passport
require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
// ******************************************
// ROUTES
// ******************************************
// Server side-rendering of root route
app.get('/', angular.serverRouter);
// API calls go here
app.use('/users', users);
// Serve static files
app.use(express.static(`${__dirname}/dist`));
// Configure Angular Express engine
app.engine('html', ngUniversal.ngExpressEngine({
bootstrap: appServer.AppServerModuleNgFactory
}));
app.set('view engine', 'html');
app.set('views', 'dist');
// Direct all other routes to index.html
app.get('*', angular.serverRouter);
// ******************************************
// API ERROR HANDLER
// ******************************************
// Error handler for 404 - Page Not Found
app.use(function (req, res, next) {
let err = new Error('Not Found');
res.status(404).json({
status: 404,
message: err.message,
name: err.name
});
});
// Error handler for all other errors
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500).json({
status: 500,
message: err.message,
name: err.name
});
});
// ******************************************
// SERVER START
// ******************************************
app.listen(port, () => console.log(`Server started on port ${port}`));