-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
79 lines (62 loc) · 1.59 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
//set header instead of cors()
// app.use((req, res, next) => {
// res.append('Access-Control-Allow-Origin', ['*']);
// res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
// res.append('Access-Control-Allow-Headers', 'Content-Type');
// next();
// });
//routes
const routes = require('./routes/index');
//body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
//cors
app.use(cors());
//dotenv config
dotenv.config();
//default port
const port = process.env.PORT || 3000;
//view engine
app.set('view engine', 'ejs');
// mongoURI
const mongoURI = process.env.DATABASE_URL;
// Connect to MongoDB
mongoose.connect(mongoURI, () => {}, {
useNewUrlParser: true
}).then(() => {
console.log("Connected to the Mongo database")
}).catch(err =>{
console.log("Could not connect to the DB at this moment",err)
process.exit();
})
//static files
app.use(express.static(path.join(__dirname, 'public')))
//routes
app.use('/', routes);
//Source not found
app.use((req,res,next) =>{
res.status(404).json({
status: 404,
msg: "Not Found"
})
})
//error 500
app.use((err,req,res,next) =>{
res.status(500).json({
status: 500,
msg: "Internal Server Error"
})
console.error(err.stack);
})
app.listen(port, () => {
console.log(`listening on port ${port} ...`)
})