-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
75 lines (66 loc) · 2.33 KB
/
app.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
var express = require('express');
var mongoose = require('mongoose');
var morgan = require('morgan');
var path = require('path');
var cors = require('cors');
var history = require('connect-history-api-fallback');
// Variables
var mongoURI = process.env.MONGODB_URI || 'mongodb://localhost:27017/animalDevelopmentDB';
var port = process.env.PORT || 3000;
// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }, function(err) {
if (err) {
console.error(`Failed to connect to MongoDB with URI: ${mongoURI}`);
console.error(err.stack);
process.exit(1);
}
console.log(`Connected to MongoDB with URI: ${mongoURI}`);
});
// Create Express app
var app = express();
// Parse requests of content-type 'application/json'
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// HTTP request logger
app.use(morgan('dev'));
// Enable cross-origin resource sharing for frontend must be registered before api
app.options('*', cors());
app.use(cors());
// Import routes
app.get('/api', function(req, res) {
res.json({'message': 'Welcome to your DIT341 backend ExpressJS project!'});
});
// Catch all non-error handler for api (i.e., 404 Not Found)
app.use('/api/*', function (req, res) {
res.status(404).json({ 'message': 'Not Found' });
});
// Configuration for serving frontend in production mode
// Support Vuejs HTML 5 history mode
app.use(history());
// Serve static assets
var root = path.normalize(__dirname + '/..');
var client = path.join(root, 'client', 'dist');
app.use(express.static(client));
// Error handler (i.e., when exception is thrown) must be registered last
var env = app.get('env');
// eslint-disable-next-line no-unused-vars
app.use(function(err, req, res, next) {
console.error(err.stack);
var err_res = {
'message': err.message,
'error': {}
};
if (env === 'development') {
// Return sensitive stack trace only in dev mode
err_res['error'] = err.stack;
}
res.status(err.status || 500);
res.json(err_res);
});
app.listen(port, function(err) {
if (err) throw err;
console.log(`Express server listening on port ${port}, in ${env} mode`);
console.log(`Backend: http://localhost:${port}/api/`);
console.log(`Frontend (production): http://localhost:${port}/`);
});
module.exports = app;