-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
66 lines (49 loc) · 1.87 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 dotenv = require('dotenv');
const path = require('path');
const cookieParser = require('cookie-parser')
const connectDB = require('./config/db');
const authRoutes = require('./routes/authRoutes');
const questionRoutes = require('./routes/questionRoutes');
const userRoutes = require('./routes/userRoutes');
const authMiddleware = require('./middleware/authMiddleware')
const Question = require('./models/Question')
const Answer = require('./models/Answer')
const { getUserProfile } = require('./controllers/userController')
dotenv.config();
connectDB();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(authMiddleware);
app.use('/api/auth', authRoutes);
app.use('/questions', questionRoutes);
app.use('/api/users', userRoutes);
app.get('/', async (req, res) => {
const questions = await Question.find().populate('user', 'username');
res.render('index', { title: 'Home', questions, user: res.locals.user });
});
app.get('/login', (req, res) => {
res.render('login', { title: 'Login'});
});
app.get('/register', (req, res) => {
res.render('register', { title: 'Register' });
});
app.get('/profile', getUserProfile);
app.get('/questions/:id', async (req, res) => {
const question = await Question.findById(req.params.id).populate('user', 'username');
const answers = await Answer.find({ question: req.params.id }).populate('user', 'username');
res.render('question', { title: 'Question', question, answers, user: req.user });
});
app.use((req, res, next) => {
const error = new Error(`Not Found - ${req.originalUrl}`);
res.status(404);
next(error);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});