-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
67 lines (59 loc) · 1.92 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
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const expressValidator = require("express-validator");
const path = require("path");
require("dotenv").config();
// import routes
const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/user");
const postRoutes = require("./routes/posts");
// app
const app = express();
// connect db - first arg is url (specified in .env)
const url = process.env.MONGODB_URI
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
mongoose.connection
.once("open", function () {
console.log("DB Connected!");
})
.on("error", function (error) {
console.log("Error is: ", error);
});
// middlewares
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
app.use(morgan("dev"));
app.use(bodyParser.json());
// saves users credentials
app.use(cookieParser());
app.use(expressValidator());
app.use(cors());
// routes middleware
// app.use(express.static(path.join(__dirname, './client/build')))
app.use('/api', authRoutes);
app.use('/api', userRoutes);
app.use('/api/post', postRoutes);
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("/*", (_, res) => {
res.sendFile(path.join(__dirname, "client/build", "index.html"));
});
}
const port = process.env.PORT || 80;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});