Created
March 27, 2019 14:04
-
-
Save vonvick/f42f54e21ca09b01064b18e03496e802 to your computer and use it in GitHub Desktop.
Entry file for express application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
import path from 'path'; | |
import bodyParser from 'body-parser'; | |
import routes from './routes'; | |
import cors from 'cors'; | |
const app = express(); | |
const router = express.Router(); | |
const headers1 = 'Origin, X-Requested-With, Content-Type, Accept'; | |
const headers2 = 'Authorization, Access-Control-Allow-Credentials, x-access-token'; | |
const whitelist = [process.env.CLIENT_URL]; | |
const corsOptionsDelegate = (req, callback) => { | |
let corsOptions; | |
if (whitelist.indexOf(req.header('Origin')) !== -1) { | |
corsOptions = { origin: true }; | |
} else if (process.env.NODE_ENV === 'production') { | |
corsOptions = { origin: true }; | |
} else { | |
corsOptions = { origin: false }; | |
} | |
callback(null, corsOptions); | |
}; | |
// setup body parser | |
app.use(bodyParser.urlencoded({ extended: true })); | |
app.use(bodyParser.json()); | |
// Use express backend routes | |
routes(router); | |
const clientHeaderOrigin = process.env.CLIENT_URL; | |
app.use(cors(corsOptionsDelegate)); | |
app.use((req, res, next) => { | |
const origin = req.headers.origin; | |
if(whitelist.indexOf(origin) > -1){ | |
res.header('Access-Control-Allow-Origin', origin); | |
} else { | |
res.header('Access-Control-Allow-Origin', clientHeaderOrigin); | |
} | |
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH, OPTIONS, PUT'); | |
res.header('Access-Control-Allow-Headers', `${headers1},${headers2}`); | |
res.header('Access-Control-Allow-Credentials', 'true'); | |
next(); | |
}); | |
// Add API Routes | |
app.use('/api', router); | |
const port = process.env.PORT || 3000; | |
// start the app by using heroku port | |
app.listen(port, () => { | |
console.log('App started on port: ' + port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment