server.js

// Setting environment variables
process.env.JWT_SECRET = 'money never sleeps';
process.env.NODE_ENV = 'local';

var NODE_ENV = {
    'production': 'Database points to mongodb web and UI fetches minified files',
    'debug'     : 'Database points to mongodb web and UI fetches unminified files',
    'nodb'      : 'App runs without database',
    'local'     : 'Database points to mongodb local and UI fetches unminified files'
};

// Setting error handler
process.on('uncaughtException', function(err) {
    console.log(err);
});

// set up ======================================================================
var express             = require('express');
var errorHandler        = require('express-error-handler');
var app                 = express(); // create our app w/ express
var mongodb             = require('mongodb'); // import the mongodb native drivers.
var Logger              = mongodb.Logger;
var port                = process.env.PORT || 7575; // set the port
var morgan              = require('morgan');
var bodyParser          = require('body-parser');
var methodOverride      = require('method-override');
var cookieParser        = require('cookie-parser');
var session             = require('express-session');
var jwt                 = require("jsonwebtoken");
var MongoStore          = require('connect-mongo')(session);
var dbConfig            = require('./app/config/dbConfig'); // load the database config
var routes              = require('./app/routes/routes.js');

// Add response headers
app.use(function(req, res, next) {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.set('Access-Control-Allow-Headers', 'Content-Type');
    res.set('Access-Control-Allow-Credentials', true);
    next();
});

// configuration ===============================================================
app.use(errorHandler({ dumpExceptions: false, showStack: false })); // npm install express-error-handler
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.set('views', __dirname + '/public'); // set static files path for jade or express engine
app.engine('.html', require('ejs').renderFile);
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({
    'extended': 'true'
}));

// parse application/x-www-form-urlencoded
// parse application/vnd.api+json as json
app.use(bodyParser.json());
app.use(bodyParser.json({
    type: 'application/vnd.api+json'
}));

// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(cookieParser());
app.use(session({
    secret: '--- OMMITTED ---',
    saveUninitialized: true,
    resave: true,
    // using store session on MongoDB using express-session + connect
    store: process.env.NODE_ENV != 'nodb' ? new MongoStore({ url: dbConfig.db.url}) : ''
}));

// We need to work with "MongoClient" interface in order to connect to a mongodb server.
var routeOptions = {};
var MongoClient = mongodb.MongoClient;
if(process.env.NODE_ENV != 'nodb') {
    MongoClient.connect(dbConfig.db.url, function(err, db) {
        if (err) {
            console.log('Unable to connect to the mongoDB server. Error:', err);
        } else {
            console.log('Database connection established to', dbConfig.db.type);

            // routes
            console.log("Initializing routes");
            routeOptions.database = db;
            routes(app, routeOptions);
            console.log("Server initialization completed");
        }
    });
}
else {
    routes(app, routeOptions);
}

// listen (start app with node server.js) ======================================
app.listen(port, function() {
    console.log('App listening on: ', port);
    console.log('Time: ' + require('./app/lib/modules/Utility').getDateTime());
});