-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
79 lines (70 loc) · 2.55 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
73
74
75
76
77
78
79
require("dotenv").config();
// Code Dependencies - Including packages and libraries
const express = require("express");
const session = require("express-session");
const path = require("path");
const bodyParser = require("body-parser");
const cors = require("cors");
const passport = require("passport");
const mongoose = require("mongoose");
const config = require("./config/database");
const app = express();
// Routes for database - directs to functions for each data block
const users = require("./routes/users");
const products = require("./routes/products");
const contact = require("./routes/contact");
// variable - Can edit which portname or port to host the website locally
const server_port = process.env.PORT || 8080;
const server_name = 'localhost';
// Connecting to Mongo database
mongoose.connect(config.database) // database is stores in the config file
.then(() => { // On Connection - Checks for connection
console.log("Connected to database: " + config.database);
})
.catch(() => { // Error Connection - Outputs error message to console if no connection
console.log("Failed to connect to database: " + config.database);
})
// Middleware
app.use(cors());
app.options("*", cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
secret: process.env.SECRET || "secret",
resave: true,
saveUninitialized: true,
maxAge: 3600000, // 1 hour (in milliseconds)
})
); // session secret
app.use(passport.initialize());
app.use(passport.session());
require("./config/passport")(passport);
// Use '/users' for all our user route functions
app.use("/users", users);
app.use("/products", products);
app.use("/contact", contact);
// Set Static Folder
if(server_port == 8080) {
app.use(express.static(path.join(__dirname + "/public/")));
app.get("/*", (req, res) => {
const fullPath = path.join(__dirname, "/public/index.html");
console.log(" Fetching from.. " + fullPath);
res.sendFile(fullPath);
});
} else {
app.use(express.static(path.join(__dirname + "/angular-src/dist/angular-src"))); // Used for deployment
app.get("/*", (req, res) => {
const fullPath = path.join(__dirname,"/angular-src/dist/angular-src/index.html");
console.log(" Fetching from.. " + fullPath);
res.sendFile(fullPath);
});
}
// Start Server
app.listen(server_port, () => {
if(server_port == 8080) { // development status
console.log(`Listening at http://${process.env.HOSTNAME}:${server_port}`);
} else { // deployment status
console.log("Server listening on port " + server_port);
}
});