-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
103 lines (81 loc) · 2.6 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
92
93
94
95
96
97
98
99
100
101
102
103
const mongoose = require("mongoose");
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require("./models/User")
require("./models/Confession")
require("./models/Topic")
const cors = require('cors');
const debug = require('debug');
const csurf = require('csurf');
const passport = require('passport');
// const indexRouter = require('./routes/index');
const usersRouter = require('./routes/api/users');
const confessionsRouter = require('./routes/api/confessions');
const csrfRouter = require('./routes/api/csrf');
const http = require('http');
const messageRoutes = require("./routes/api/messages")
const topicsRouter = require('./routes/api/topics');
const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
const { isProduction } = require('./config/keys');
if (!isProduction) {
app.use(cors());
}
app.use(
csurf({
cookie: {
secure: isProduction,
sameSite: isProduction && "Lax",
httpOnly: true
}
})
);
// app.use('/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/csrf', csrfRouter);
app.use('/api/messages', messageRoutes)
app.use('/api/confessions', confessionsRouter);
app.use('/api/topics', topicsRouter);
// Serve static React build files statically in production
if (isProduction) {
const path = require('path');
// Serve the frontend's index.html file at the root route
app.get('/', (req, res) => {
res.cookie('CSRF-TOKEN', req.csrfToken());
res.sendFile(
path.resolve(__dirname, './frontend', 'build', 'index.html')
);
});
// Serve the static assets in the frontend's build folder
app.use(express.static(path.resolve("./frontend/build")));
// Serve the frontend's index.html file at all other routes NOT starting with /api
app.get(/^(?!\/?api).*/, (req, res) => {
res.cookie('CSRF-TOKEN', req.csrfToken());
res.sendFile(
path.resolve(__dirname, './frontend', 'build', 'index.html')
);
});
}
app.use((req, res, next) => {
const err = new Error("Not Found");
err.statusCode = 404;
next(err);
});
const serverErrorLogger = debug('backend:error');
app.use((err, req, res, next) => {
serverErrorLogger(err);
const statusCode = err.statusCode || 500;
res.status(statusCode);
res.json({
message: err.message,
statusCode,
errors: err.errors
})
});
module.exports = app;