-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
65 lines (55 loc) · 1.8 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
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
const productRoutes = require('./routes/productRoutes');
const locationRoutes = require('./routes/locationRoutes');
const dotenv = require('dotenv');
// Load environment variables from .env file
dotenv.config();
const app = express();
const PORT = process.env.PORT || 10000;
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI).then(() => {
console.log('MongoDB connected');
}).catch(err => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET || 'yourSecret',
resave: false,
saveUninitialized: true
}));
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/home', (req, res) => {
res.render('index', { user: req.session.user });
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/public/home.html");
});
// Routes
app.use('/users', userRoutes);
app.use('/products', productRoutes);
app.use('/locations', locationRoutes);
// app.use('/locations', locationRoutes) tells the main Express application to use the locationRoutes router for any request that starts with /locations.
app.get('/dashboard', (req, res) => {
if (!req.session.user) {
return res.status(401).redirect('/login');
}
res.render('index', { user: req.session.user });
});
app.get('/signup', (req, res) => {
res.render('signup');
});
app.get('/login', (req, res) => {
res.render('login');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});