-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
72 lines (62 loc) · 1.77 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
65
66
67
68
69
70
71
72
const express = require("express");
const session = require("express-session");
const rateLimit = require("express-rate-limit");
const cors = require("cors");
const MongoStore = require("connect-mongo");
const mongoose = require("mongoose");
const path = require("path");
const app = express();
const users = require("./routes/api/users");
// Config from Environment variables
const keys = {};
keys.sessionSecret = process.env.APP_SESSIONSECRET;
keys.clientUrl = process.env.APP_CLIENTURL;
keys.db = process.env.APP_DB;
// Enable CORS
app.use(
cors({
origin: [/*'http://localhost:3000',*/ keys.clientUrl],
methods: ["GET", "POST"],
credentials: true, // enable set cookie (needed for AXIOS frontend requests)
})
);
// Rate Limiter Middleware
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 1000, // limit each IP to 1000 requests per windowMs
});
app.use(limiter);
// Body parser middleware
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// Connect to Mongo DB using Mongoose
mongoose.connect(keys.db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
mongoose.connection.on("error", () =>
console.error.bind(console, "connection error")
);
mongoose.connection.once("open", () => {
console.log("MongoDB successfully connected");
});
const mongoStore = MongoStore.create({
mongoUrl: keys.db,
mongoOptions: {
useNewUrlParser: true,
useUnifiedTopology: true,
},
});
// Session Middleware
app.use(
session({
secret: keys.sessionSecret,
saveUninitialized: false, // don't create session until something stored
resave: false, //don't save session if unmodified
store: mongoStore,
})
);
// Routes
app.use("/api/users", users);
module.exports = { app, mongoStore };