-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathapp.js
91 lines (69 loc) · 2.25 KB
/
app.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Package Dependencies
const bodyParser = require('body-parser');
const express = require('express');
const helmet = require('helmet');
const mongoose = require('mongoose');
const morgan = require('morgan');
// Local Dependencies
const { DB_URL, NODE_ENV: ENV } = require('./config');
// Instantiate Express Server
const app = express();
/**
* MONGODB CONNECTION
*/
// Setup MongoDB connection using the global promise library and then get connection
mongoose.connect(DB_URL, { promiseLibrary: global.Promise }, (error) => {
if (error) {
console.log(`MongoDB connection error: ${error}`);
// should consider alternative to exiting the app due to db conn issue
process.exit(1);
}
});
const db = mongoose.connection;
/**
* MIDDLEWARE
*/
// Set security-related HTTP headers (https://expressjs.com/en/advanced/best-practice-security.html#use-helmet)
app.use(helmet());
// Allow access on headers and avoid CORS issues
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Access, Authorization, x-access-token',
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, PATCH, DELETE');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Access, Authorization, x-access-token',
);
return res.status(200).json({});
}
next();
});
// Parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Log every request to the console
app.use(morgan('dev'));
/**
* ROUTES
*/
// API Routes
// app.use('/', require('./routes/index'));
app.use('/map', require('./routes/map'));
app.use('/search', require('./routes/search'));
app.use('/users', require('./routes/users'));
// TODO: Create additional routes as necessary
// Serve static assets and index.html in production
if (ENV === 'production') {
// Serve static assets
app.use(express.static('client/build'));
// Serve index.html file if no other routes were matched
const { resolve } = require('path');
app.get('**', (req, res) => {
res.sendFile(resolve(__dirname, 'client', 'build', 'index.html'));
});
}
module.exports = app;