forked from olinations/crud-starter-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
65 lines (56 loc) · 1.81 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
const express = require('express')
// use process.env variables to keep private variables,
// be sure to ignore the .env file in github
require('dotenv').config()
// Express Middleware
const helmet = require('helmet') // creates headers that protect from attacks (security)
const bodyParser = require('body-parser') // turns response into usable format
const cors = require('cors') // allows/disallows cross-site communication
const morgan = require('morgan') // logs requests
// db Connection w/ Heroku
// const db = require('knex')({
// client: 'pg',
// connection: {
// connectionString: process.env.DATABASE_URL,
// ssl: true,
// }
// });
// db Connection w/ localhost
var db = require('knex')({
client: 'pg',
connection: {
host : '127.0.0.1',
user : '',
password : '',
database : 'crud-starter-api'
}
});
// Controllers - aka, the db queries
const main = require('./controllers/main')
// App
const app = express()
// App Middleware
const whitelist = ['http://localhost:3001']
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(helmet())
app.use(cors(corsOptions))
app.use(bodyParser.json())
app.use(morgan('combined')) // use 'tiny' or 'combined'
// App Routes - Auth
app.get('/', (req, res) => res.send('hello world'))
app.get('/crud', (req, res) => main.getTableData(req, res, db))
app.post('/crud', (req, res) => main.postTableData(req, res, db))
app.put('/crud', (req, res) => main.putTableData(req, res, db))
app.delete('/crud', (req, res) => main.deleteTableData(req, res, db))
// App Server Connection
app.listen(process.env.PORT || 3000, () => {
console.log(`app is running on port ${process.env.PORT || 3000}`)
})