-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
67 lines (52 loc) · 1.47 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
import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import mongoose from 'mongoose'
import setApp from './api.js'
import path from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
dotenv.config()
const PORT = process.env.PORT
const URL = process.env.MONGODB_URI
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
)
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, DELETE, OPTIONS'
)
next();
})
const connectDB = async () => {
try {
const conn = await mongoose.connect(URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log(`MongoDB connected: ${conn.connection.host}`)
} catch (error) {
console.log(error)
process.exit(1)
}
}
connectDB()
setApp(app)
//listening on port
app.listen(PORT, () => {
console.log('Server listening on port ' + (PORT));
})
if (process.env.PROD) {
app.use(express.static(path.join(__dirname, 'frontend/build')))
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'frontend/build', 'index.html'));
})
}