-
Notifications
You must be signed in to change notification settings - Fork 49
/
server.js
64 lines (50 loc) · 1.64 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
require('module-alias/register');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var chalk = require('chalk');
var config = require('./config');
require('dotenv').config();
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// Allow CORS
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.get('/favicon.ico', (req, res) => {
res.sendFile(`${__dirname}/static/favicon.ico`);
});
// Backend API routes
app.use(require('./src/backend/routes')());
// Catch any errors
app.use((err, req, res, next) => {
if (err) {
res.error(`There was an error parsing the request: ${err}`);
return;
}
next();
});
// Frontend endpoints
app.use(express.static(__dirname + '/dist'));
app.use('/', express.static(__dirname + '/dist'));
// Catch all for frontend routes
app.all('/*', function(req, res) {
res.sendFile(path.join(__dirname, '/dist', '/index.html'));
});
const PORT = process.env.PORT || config.port;
app.listen(PORT);
console.log(chalk.green('Started on port ' + PORT));
// Connect to MongoDB
const DATABASE = process.env.NODE_ENV === 'production' ? process.env.MONGODB_URI : config.database;
mongoose.Promise = global.Promise;
mongoose.connect(DATABASE, { useNewUrlParser: true, useUnifiedTopology: true })
.then(res => {
console.log(chalk.green('Connected to MongoDB: ' + DATABASE));
}).catch(err => {
console.log(chalk.red('Error connecting to MongoDB: ' + err));
}
);