-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.js
81 lines (67 loc) · 2.33 KB
/
index.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
// Importing Node modules and initializing Express
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
logger = require('morgan'),
router = require('./helpers/router'),
mongoose = require('mongoose'),
config = require('./config/config'),
helpers = require('./helpers/helpers');
const path = require('path');
const debug = require('debug')('mon-gen:server');
// Database Setup
if (process.env.NODE_ENV !== config.testEnv) {
mongoose.connection.openUri(config.database);
} else {
mongoose.connection.openUri(config.database);
}
mongoose.connection.on('connected', function(ref) {
helpers.isAdminExists();
});
// Start the server
let server;
if (process.env.NODE_ENV !== config.testEnv) {
const port = helpers.normalizePort(config.port);
const host = config.host || '0.0.0.0';
server = app.listen(port, host);
} else {
server = app.listen(config.testPort);
}
// If the connection throws an error
mongoose.connection.on('error', function(err) {
console.error('Failed to connect to DB on startup ');
process.exit(0);
});
server.on('listening', function() {
console.log(
`Express server started on port ${server.address().port} at ${server.address().address}`
);
});
// Setting up basic middleware for all Express requests
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
// Enable CORS from client-side
app.use((req, res, next) => {
// res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS, PATCH');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials'
);
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
// Import routes to be served
router(app);
// // Serve static assets
app.use(express.static(`${__dirname}/public/build`));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public/build', 'index.html'));
});
const socketIO = require('socket.io');
let io = socketIO(server);
require('./controllers/socketEvents')(io);
// necessary for testing
module.exports = server;