forked from Ross-Rogerson/Travel-Website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (38 loc) · 1.24 KB
/
index.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
import express from 'express'
import mongoose from 'mongoose'
import router from './config/router.js'
import 'dotenv/config'
import path, { dirname } from 'path'
import { fileURLToPath } from 'url'
const app = express()
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const startServer = async () => {
try {
// ? Connect to our mongodb database
await mongoose.connect(process.env.MONGO_URI)
console.log('Database connected')
app.use(express.json())
// ? Middleware
// logger
app.use((req, res, next) => {
console.log(`incoming requests: ${req.method} ${req.url}`)
next()
})
// Routes
app.use('/api', router)
app.use(express.static(path.join(__dirname, 'client', 'build')))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'))
})
// 404 catach all middleware
app.use((req, res) => {
return res.status(404).json({ message: 'Route not found' })
})
app.listen(process.env.PORT, () => console.log(`Server is up and running and listening to port ${process.env.PORT}`))
} catch (err) {
console.log('There was an error starting the database')
console.log(err)
}
}
startServer()