-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
63 lines (53 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
const express = require('express');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const logging = require('./lib/logging');
const app = express();
/**
* Load environment variables from .env file
*/
dotenv.config();
/**
* Connect to MongoDB.
*/
if (process.env.MONGODB_URI) {
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
throw new Error(
'MongoDB Connection Error. Please make sure that MongoDB is running.'
);
});
}
// Add the request logger before anything else so that it can
// accurately log requests.
// [START requests]
app.use(logging.requestLogger);
// [END requests]
app.set('port', process.env.PORT || 3001);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Express only serves static assets in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
// The error handler must be before any other error middleware
app.use(logging.errorLogger);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
// no stacktraces leaked to user unless in development environment
app.use((err, req, res) => {
res.status(err.status || 500).send({
message: err.message,
error: app.get('env') === 'development' ? err : {},
});
});
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`); // eslint-disable-line no-console
});