-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
53 lines (38 loc) · 1.19 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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./config/db');
// Use Node's default promise instead of Mongoose's promise library
mongoose.Promise = global.Promise;
// Connect to the database
mongoose.connect(config.db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let db = mongoose.connection;
db.on('open', () => {
console.log('Connected to the database.');
});
db.on('error', (err) => {
console.log(`Database error: ${err}`);
});
// Instantiate express
const app = express();
// Set public folder using built-in express.static middleware
app.use(express.static('public'));
// Set body parser middleware
app.use(bodyParser.json());
app.use(cors());
// Initialize routes middleware
app.use('/api/test-records', require('./routes/test_records'));
// Use express's default error handling middleware
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
res.status(400).json({ err: err });
});
// Start the server
const port = process.env.PORT || 3001;
const server = app.listen(port, () => {
console.log(`Listening on port ${port}`);
});