-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
60 lines (49 loc) · 1.91 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
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import morgan from 'morgan';
// We gotta import our models and routes
import Game from './app/models/game';
import { getGames, getGame, postGame, deleteGame } from './app/routes/game';
const app = express(); // Our express server!
const port = process.env.PORT || 8080;
// DB connection through Mongoose
const options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }
}; // Just a bunch of options for the db connection
mongoose.Promise = global.Promise;
// Don't forget to substitute it with your connection string
mongoose.connect('YOUR_MONGO_CONNECTION', options);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
// Body parser and Morgan middleware
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
// We tell express where to find static assets
app.use(express.static(__dirname + '/client/dist'));
// Enable CORS so that we can make HTTP request from webpack-dev-server
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// API routes
app.route('/games')
// create a game
.post(postGame)
// get all the games
.get(getGames);
app.route('/games/:id')
// get a single game
.get(getGame)
// delete a single game
.delete(deleteGame);
// ...For all the other requests just sends back the Homepage
app.route("*").get((req, res) => {
res.sendFile('client/dist/index.html', { root: __dirname });
});
app.listen(port);
console.log(`listening on port ${port}`);