-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
64 lines (50 loc) · 1.97 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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes/index.js');
// Auth libraries
const passport = require('passport');
const session = require('express-session')
const app = express();
// Load .env variables
require('dotenv').load();
// passport.js contains the Passport auth strategies. Currently only GitHub
require('./auth/passport')(passport);
const port = process.env.PORT || 3001;
// Connect to MongoDB database
const mongoDB = process.env.MONGODB_URI;
mongoose.connect(mongoDB, { useMongoClient: true })
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// Configure body parser for json format
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Initialize Express Session
app.use(session({
secret: 'bears-20',
resave: false,
saveUninitialized: true
}));
// Initialize Passport for authentication
app.use(passport.initialize());
app.use(passport.session());
// Set Headers to allow Cross Origin Requests
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
next();
});
// Serve static assets
app.use(express.static(path.resolve('build')));
// Connect all our routes to our application
app.use('/', routes);
// If request doesn't match api request always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
res.sendFile(path.resolve('build', 'index.html'));
});
app.listen(port, function() {
console.log(`API running on port ${port}`);
});