-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (58 loc) · 1.65 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const path = require('node:path')
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const cors = require('cors')
const compression = require('compression')
const dotenv = require('dotenv')
const Poem = require('./models/poem')
const poemRoutes = require('./routes/poems')
dotenv.config()
// Environment Variables
const PORT = process.env.PORT
const DB_URL = process.env.MONGODB_URI
// MongoDB Connection
mongoose
.connect(DB_URL)
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Failed to connect to MongoDB', err))
// Express Server
const app = express()
app.use(compression())
app.use(
cors({
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
credentials: true
})
)
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs')
app.use('/poems', poemRoutes)
// Root Route
app.get('/', (req, res) => {
res.render('index')
})
// Home Route
app.get('/home', (req, res) => {
res.render('index')
})
// Search route
app.get('/search', async (req, res) => {
const query = req.query.query
try {
const poemsByTitle = await Poem.find({ title: new RegExp(query, 'i') })
const poemsByAuthor = await Poem.find({ author: new RegExp(query, 'i') })
res.render('search', { query, poemsByTitle, poemsByAuthor })
} catch (err) {
console.error(err)
res.status(500).send(err.message)
}
})
// Listen to the PORT
const server = app.listen(PORT, () => {
console.log(`Server is running on port \`${PORT}\``)
})
module.exports = { app, server }