-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (53 loc) · 1.53 KB
/
server.js
File metadata and controls
65 lines (53 loc) · 1.53 KB
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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');
const mongoose = require('mongoose')
const path = require("path")
const app = express();
const port = process.env.PORT || 4000;
const inventoryRoutes = require('./routes/inventory')
app.use(morgan('tiny'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.use(bodyParser.json());
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static('client/build/'))
app.get('/*', function(req, res) {
res.sendFile(path.resolve(__dirname, 'client/build/'))
})
}
// Connection URL
const uri = process.env.MONGODB_URI
// Initialize Connection Once and Create Connection Pool
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true},
function(err) {
if (err) throw err;
console.log('Database Connected');
})
// Routes that should handle requests
app.use('/inv', inventoryRoutes);
// Catch errors that go beyond the above routes
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
})
// Passes direct errors
app.use((error, req, res, next) =>{
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
app.listen(port, function() {
console.log("Server is running on Port: " + port)
})