forked from freeCodeCamp/boilerplate-project-exercisetracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
51 lines (41 loc) · 1.34 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
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const cors = require('cors')
let usersRouter = require('./app/routers/users.router.js')
const db = require('./app/config/mongodb.env.js')
const mongoose = require('mongoose')
mongoose.set('useCreateIndex', true)
mongoose.connect(db.MONGO_DB_URI, { useNewUrlParser: true })
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
app.use('/api/exercise',usersRouter)
// Not found middleware
app.use((req, res, next) => {
return next({status: 404, message: 'not found'})
})
// Error Handling middleware
app.use((err, req, res, next) => {
let errCode, errMessage
if (err.errors) {
// mongoose validation error
errCode = 400 // bad request
const keys = Object.keys(err.errors)
// report the first validation error
errMessage = err.errors[keys[0]].message
} else {
// generic or custom error
errCode = err.status || 500
errMessage = err.message || 'Internal Server Error'
}
res.status(errCode).type('txt')
.send(errMessage)
})
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})