This repository was archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (68 loc) · 1.92 KB
/
server.js
File metadata and controls
80 lines (68 loc) · 1.92 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 passport = require('passport');
require('dotenv').config();
const auth = require('./routes/users');
const inventory = require('./routes/inventory');
const app = express();
const port = process.env.PORT || 4000;
// Middlewares
app.use(morgan('tiny'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(bodyParser.json());
if (process.env.NODE_ENV === 'production') {
// Force SSL/HTTPS
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`);
} else {
next();
}
});
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
app.get(/^\/(?!api).*/, (req, res) => {
res.sendFile('index.html', { root: path.join(__dirname, 'client/build') });
});
}
// Initialize connection once and create connection pool
mongoose
.connect(
process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
},
)
.then(() => console.log('Database Connected'))
.catch((err) => console.log(err));
// Passport middleware
app.use(passport.initialize());
require('./config/passport')(passport);
// Routes that should handle requests
app.use('/api/auth', auth);
app.use('/api/inv', inventory);
// 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,
},
});
next(error);
});
app.listen(port, () => {
console.log(`Server is running on Port: ${port}`);
});